当前位置: 首页 > news >正文

Shell编程--流程控制

目录

  • 1.条件结构
    • 1.1.文件测试(字符串)
    • 1.2.字符串比较
    • 1.3.数字条件比较
    • 1.4.文件条件判断
  • 2.if多条件判断
  • 3.case语句

1.条件结构

测试:test 条件
        条件为真返回 0,条件为假返回 1
语法:[ 条件 ]
test 条件能够理解以下类型的表达式

1.1.文件测试(字符串)

-n STRING
the length of STRING is nonzero
-n 字符串的长度 【不是】零成功。

​-n不为空案例:

[root@localhost ~]# vim a.sh
#!/usr/bin/bash
read -p "请输入幸运数字" lucky_num
if [[ -n $lucky_num ]]; thenecho "您的幸运数字是$lucky_num"
elseecho "您输入的幸运数字为空"exit
fi
//执行:
[root@localhost ~]# bash a.sh
请输入幸运数字12
您的幸运数字是12
[root@localhost ~]# bash a.sh
请输入幸运数字
您输入的幸运数字为空

-z STRING
        the length of STRING is zero
-z 字符串长度【是】零成功
对于未定义或赋予空值的变量将是为空串。

-z为空案例,为空时则执行

[root@localhost ~]# cat b.sh
#!/usr/bin/bash
read -p "请输入幸运数字" lucky_num
if [[ -z $lucky_num ]]; thenecho "您输入的幸运数字为空"
elseecho "您输入的幸运数字为$lucky_num"exit
fi
//执行:
[root@localhost ~]# bash b.sh
请输入幸运数字         #不输入,留空
您输入的幸运数字为空
[root@localhost ~]# bash b.sh
请输入幸运数字23       #输入数字
您输入的幸运数字为23[root@localhost ~]# vim string.sh
#!/bin/bash
while :
doread -p "请输入你的密码:" passpasswd=12345if [[ -z $pass ]];thenecho "您输入的密码不能为空"exit 1elseif [[ $pass == $passwd  ]];thenecho  "密码输入成功"breakelseecho "您输入的密码有误,请重新输入"               fifi
done

1.2.字符串比较

STRING1 = STRING2 (等于)
        the strings are equal
STRING1 != STRING2 (不等于)
        the strings are not equal

1.3.数字条件比较

格式含义
-eq(equal)等于
-ne(not equal)不等于
-ge(Greater than or equal to)大于等于
-le(Less than or equal to)小于等于
-gt(greater than)大于
-lt(less than)小于

1.4.文件条件判断

格式含义
-f存在且是正规文件
-d存在且是目录
-h存在且是符号链接
-b块设备
-c字符设备
-e文件存在
[root@localhost ~]# vim file.sh
#!/bin/bash
file=/root/test.txt
if [[ -e $file ]];thenecho "$file"
elseecho "文件不存在"  touch $file &&  echo "文件已创建"
fi

2.if多条件判断

流程控制:在一个shell脚本中的【命令执行的顺序】称作脚本的流。大多数脚本会根据一个或多个条件来改变它们的流。
流控制命令:能让脚本的流 根据条件而改变的命令,称为条件流控制命令
exit语句:退出程序的执行,并返回一个返回码,返回码为0正常退出,非0为非正常退出,例如: exit 0
条件判断语法:​if 代码返回0表示真,非0为假

if语句语法如下:
if [[ -e -eq -ne ]];then  //-e -eq -ne是你的测试条件,你要测试什么,对什么内容做判断(例如$? -eq 0)list1                 //执行list2里面的内容
elif [[ -e -eq ]];then    //接着在怎么做。(多条件判断)list2
else                      //如果前面的命令没有执行成功那就执行else下面的命令。list3
fi
[root@localhost ~]# cd /opt/test/script/
[root@localhost script]# vim testif.sh
#!/bin/bash
read -p "请输入号码: " num 
if [[ $num = 1 ]];thenecho "1"
elif [[ $num = 2 ]];thenecho "2"
elif [[ $num = 3 ]];thenecho "3"
else echo "输入有误!"
fi
[root@localhost script]# bash testif.sh

例:脚本if.sh,必须在脚本后加上适当的参数脚本才能正确执行

[root@localhost script]# vim if.sh
#!/bin/bash
if [[ "$1" = "hello" ]]; thenecho "Hello! How are you ?"
elif [[ "$1" = "" ]]; thenecho "You MUST input parameters"
elseecho "The only accept parameter is hello"
fi
[root@localhost script]# chmod +x if.sh
//测试:
[root@localhost script]# ./if.sh 
[root@localhost script]# ./if.sh hello
[root@localhost script]# ./if.sh 434

​练习:
(1)检测nginx是否已经安装、已经运行,如果没有安装和运行则【安装并启动】,并【记录启动】的时间,保存到日志中。

#!/bin/sh
#check_nginx_install
nginx -V
if [[ $? -ne 0 ]]; thenyum -y install nginx
fi
#check_nginx_status
ps -ef|grep nginx && netstat -ntlp|grep nginx
if [[ $? -ne 0 ]]; thensystemctl restart nginx 
fi
#record_nginx_up_time
up_time=$(systemctl status nginx.service |grep -i active|awk '{print $6,$7}')
echo $up_time > /root/nginx_up_time

(2)测试ip地址主机位从2到100的机器是否存活,并把存活的机器记录到文本文件alivehost.txt内。(使用ping命令)

#!/usr/bin/bash
ip=192.168.17
for i in {2..100}
doping -c1 -w1 $ip.$i &> /dev/nullif [ $? -eq 0 ];thenecho "$ip.$i is up" >> activehost.txtelseecho "$ip.$i is down" &> /dev/nullfi
done

多个条件联合:

&&:逻辑与,前面执行成功,后面才执行。前面命令执行失败,后面命令也不执行
if [ $condition1 ] && [ $condition2 ];then
if [[ $condition1 && $condition2 ]];then

||:逻辑或,前面执行失败,后面执行,前面命令执行成功,后面不执行。
if [ $condition1 ] || [ $condition2 ];then
if [[ $condition1 || $condition2 ]];then

拓展知识:[[ ]]和[ ]的区别

[[ ]]支持正则表达式,而[ ]不支持
例如:
      [[ $a == z* ]] # 正则匹配
      [ $a == z* ] # 无效
[ ] 语法 都可以由 [[ ]] 替代,并且后者功能更丰富
[ ] 使用 -a、-o 分别表示与、或 关系 ,[[ ]]使用 &&、 ||表示与 、或关系
而且在使用中,[[ ]]比[ ]更加的稳定,在脚本的使用中,建议使用[[ ]]

1. 判断一个用户是否存在
2. 判断当前内核主版本是否为3,且次版本是否大于10//主版本获取:uname -r|cut -d. -f1    #-d.    以什么为分隔符 -f1打印第一段3//次版本获取uname -r|cut -d. -f210//或者:[root@localhost ~]# uname  -r|awk -F'.' '{print $1}'3[root@localhost ~]# uname  -r|awk -F'.' '{print $2}'10
3. 判断vsftpd软件包是否安装,如果没有则自动安装 (yum是否能用,不能用自动修复,安装完成测试下,是否能用。)
4. 判断httpd是否运行
5. 判断指定的主机是否能ping通,必须使用$1变量
ping -c1 -w1 $1.com

3.case语句

case 语句是 shell 中流控制的第二种方式,语法如下:
case $变量 inpattern1)list1;;          //2个英文的分号结尾。pattern2)list2;;... ...patternN)listN;;*)                //如果前面命令没有执行成功那么执行下面这个list*;;
esac        //结尾

​第一行:声明case关键字调用case语法,紧跟的“变量”一般为用户的输入值, in代表从下方的各个模式进行匹配
第2-4行:匹配到“pattern1”后进行命令的输出或执行, pattern1: 一般为字符或数值
第11-12行:当用户输入的字符不存在匹配模式时, 直接执行或打印
)下的命令或语句
*

[root@localhost script]# vim case1.sh
#!/usr/bin/env bash
case $1 ina)echo "one";;b)echo "two";;*)echo "Usage:$0 '{a|b}'"    # $0就是这个脚本;;
esac
​//执行结果
[root@localhost ~]# bash case.sh
Usage:case.sh '{a|b}'
[root@localhost ~]# bash case.sh a
one
[root@localhost ~]# bash case.sh b
two

练习:
建立脚本case2.sh,当执行时,要求我们在键盘输入适当的值(数字),当输入正确时并打印,当输入错误时会提示你,应该输入正确的值。

[root@localhost script]# vim case3.sh
#!/usr/bin/env bash
read -p "请输入:" get
case $get in
[0-9][0-9])echo -e "你输入的是数字,为:$get\n";;
*)echo -e "你输入的不是数字。\n";;
esac

示例:编写系统工具脚本

[root@localhost script]# vim system_tools.sh
#!/usr/bin/env bash
#cat <<-EOF
echo '
+-------------------------------------------------------------------------+
|                             System_tools V1.0                           |
+-------------------------------------------------------------------------+
|                     a. Stop And Disabled Firewalld.                     |
|                     b. Disabled SELinux Secure System.                  |
|                     c. Install Apache Service.                          |
|                     d. Quit                                             |
+-------------------------------------------------------------------------+
'
#EOF
read -t 60 -p "请在1分钟内作出选择"  choose
case "$choose" in"a")systemctl stop firewalld && systemctl disable firewalld;;"b")setenforce 0;;"c")yum -y install httpd httpd-tools;;"d")exit;;*)printf "请按照上方提供的选项输入!!!\n";;
esac
[root@localhost script]# chmod +x system_tools.sh
[root@localhost script]# ./system_tools.sh

练习:
建立脚本service.sh,当用户执行的时候要求输入(1、2、3、4、5)时安装对应的httpd、vim、wget、更换aliyun yum源等功能,当输入错误时会提示你,应该输入正确的值。

[root@localhost ~]# vim service.sh
#!/bin/bash
echo '
+-------------------------------------------------------------------------+
|                             System_tools V1.0                           |
+-------------------------------------------------------------------------+
|                     1. Install Apache Service.                          |
|                     2. Install Vim.                                     |
|                     3. Install Wget.                                    |
|                     4. Change Aliyun Yum.                               |
|                     5. Change Tencent Yum.                              |
|                     6. Quit                                             |
+-------------------------------------------------------------------------+
'
read -t 60 -p "请在1分钟内作出选择"  choose
case "$choose" in"1")yum -y install httpd httpd-tools;;"2")yum -y install vim;;"3")yum -y install wget;;"4")yum -y install wgetmv /etc/yum.repos.d/* /tmpwget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repowget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repoyum makecacheyum repolist;;"5")yum -y install wgetmv /etc/yum.repos.d/* /tmpwget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.cloud.tencent.com/repo/centos7_base.repowget -O /etc/yum.repos.d/epel.repo http://mirrors.cloud.tencent.com/repo/epel-7.repoyum makecacheyum repolist;;"6")exit;;*)echo -e "请按照上方提供的选项输入!!!\n";;
esac[root@localhost ~]# bash service.sh
+-------------------------------------------------------------------------+
|                             System_tools V1.0                           |
+-------------------------------------------------------------------------+
|                     1. Install Apache Service.                          |
|                     2. Install Vim.                                     |
|                     3. Install Wget.                                    |
|                     4. Change Aliyun Yum.                               |
|                     5. Change Tencent Yum.                              |
|                     6. Quit                                             |
+-------------------------------------------------------------------------+
请在1分钟内作出选择 
http://www.lryc.cn/news/230314.html

相关文章:

  • 设计模式-模板方法模式(Template Method)
  • 远程登录Linux方法(Linux平台相互远程;Windows远程登录Linux、远程编码、文件传输;无法远程登录的问题解决;c程序的编译)
  • macOS 13.6 及后续系统安装 Asahi Linux 将破坏引导
  • Python武器库开发-flask篇之flask框架的安装(二十一)
  • 【CASS精品教程】打开cass提示base.dcl未找到文件的解决办法
  • [vim]Python编写插件学习笔记3 - 命令行参数
  • 【仙逆】王林400年晋升元婴,复仇藤化元杀尽藤姓,高老畏罪自裁
  • 云原生实战课大纲
  • 数据湖架构
  • Zabbix 5.0部署(centos7+server+MySQL+Apache)
  • YOLO改进系列之注意力机制(CloAttention模型介绍)
  • openssl+AES开发实例(linux)
  • FreeRTOS源码阅读笔记3--queue.c
  • 云原生Kubernetes系列 | 通过容器互联搭建wordpress博客系统
  • java读取OPC DA数据---Utgard
  • 在 Android 上简单安全地登录——使用凭证管理器和密钥
  • 【Python】上市公司数据进行经典OLS回归实操
  • 科研学习|科研软件——有序多分类Logistic回归的SPSS教程!
  • 微服务简单理解与快速搭建
  • QColorDialog开发实例
  • linux实现全局快捷键
  • 共享台球室小程序系统:智能化预约与管理
  • 百度文心一言
  • 225.用队列实现栈(LeetCode)
  • 汽车FMCW毫米波雷达信号处理流程(推荐---基础详细---清楚的讲解了雷达的过程---强烈推荐)
  • 8.指令格式,指令的寻址方式
  • k8s自定义Endpoint实现内部pod访问外部应用
  • [100天算法】-分割等和子集(day 78)
  • 共享台球室小程序系统的数据统计与分析功能
  • Istio学习笔记- 服务网格