【Linux】shell脚本实战-if多分支条件语句详解

前言

前面我们已经学习过单分支语句和双分支语句的使用。 双分支语句就是在单分支语句的基础上又加了一层结果项。
今天我们来探讨下多分支语句,顾名思义,多分支语句就是在双分支语句基础上又加了一个可能性的结果
如果你还没有学习单双分支条件语句,建议参考下方链接学习:

【Linux】shell脚本实战-if单双分支条件语句详解

多分支语句的语法

语法结构:

if条件测试操作1 ; then
		commands
elif  条件测试操作2  ; then
		commands
elif 条件测试操作3 ; then
		commands
.......
else
		commands
fi

举例:

if [ 你有钱 ]
  then
     我就嫁给你
elif [ 家庭有背景 ]
  then
     也嫁给你
elif [ 有权 ]
  then
     也嫁给你
else
     我考虑下
fi

多分支语句的图示:
在这里插入图片描述

多分支语句举例:

1. 出嫁的条件
[root@ecs-c13b ~]# cat ifdtest1 
#!/bin/bash
read -p "请输入你有多少钱: " money
read -p "请输入你有几套房子: " houses

if [ $money -ge 1000000 ]   ### ge 表示大于
  then
     echo "我就嫁给你"
elif [ $houses -ge 3 ]
  then
     echo "我也嫁给你"
else
     echo "我考虑下"
fi

返回结果:

[root@ecs-c13b ~]# bash ifdtest1 
请输入你有多少钱: 100000
请输入你有几套房子: 5
我也嫁给你
2. 管理http服务实战脚本
[root@ecs-c13b html]# cat httpdcheck.sh 
#!/bin/bash
ss -lntp |grep httpd &> /dev/null
if [ $? -eq 0 ];then
	echo "httpd is running"
elif [ -f /usr/local/apache/bin/apachectl -a -x /usr/local/apache/bin/apachectl ]
### 查看文件是否存在且是否有可执行权限
  then
    /usr/local/apache/bin/apachectl start
    #### 如果有可执行权限,且存在,就执行脚本启动
else
  echo "没有httpd的启动脚本"
fi

返回结果:

[root@ecs-c13b html]# bash httpdcheck.sh 
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, usingrName' directive globally to suppress this message
[root@ecs-c13b html]# lsof -i:80
COMMAND   PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
httpd   31393   root    4u  IPv6 363012      0t0  TCP *:http (LISTEN)
httpd   31394 daemon    4u  IPv6 363012      0t0  TCP *:http (LISTEN)
httpd   31395 daemon    4u  IPv6 363012      0t0  TCP *:http (LISTEN)
httpd   31399 daemon    4u  IPv6 363012      0t0  TCP *:http (LISTEN)
[root@ecs-c13b html]# bash httpdcheck.sh 
httpd is running
3. 猜数字游戏v1版本-if版本
#!/bin/bash
NO=20

read -p "input your num: " num
if [ $NO -gt $num ]; then   ### 判断输入的数字和原始数字的大小,gt表示大于
	echo "你猜测的太小了"
elif [ $NO -lt $num ]; then  ####判断输入的数字和原始数字的大小,lt表示小于
	echo "你猜测的太大了"
else 
	echo "恭喜你猜对了"

fi

返回结果:

[root@ecs-c13b html]# vim guess.sh
\[root@ecs-c13b html]# bash guess.sh 
input your num: 33
你猜测的太大了
[root@ecs-c13b html]# bash guess.sh 
input your num: 1
你猜测的太小了
[root@ecs-c13b html]# bash guess.sh 
input your num: 20
恭喜你猜对了

总结

多条件语句相对单双条件语句来说,稍微困难一些,但只要稍加练习就可以熟练。

猜你喜欢

转载自blog.csdn.net/xinshuzhan/article/details/107827399