今天学习Shell 流程控制
一、if else
1.if语句语法格式:
if conditionthen command1 command2 ... commandN fi
写成一行(适用于终端命令提示符):
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
2.if else语法格式:
if conditionthen command1 command2 ... commandNelse commandfi
3.if else-if else 语法格式:
if condition1then command1elif condition2 then command2else commandNfi
if else 的 [...] 判断语句中大于使用 -gt,小于使用 -lt。
if [ "$a" -gt "$b" ]; then ...fi
如果使用 ((...)) 作为判断语句,大于和小于可以直接使用 > 和 <。
if (( a > b )); then ...fi
以下实例判断两个变量是否相等:
a=10b=20if [ $a == $b ]then echo "a 等于 b"elif [ $a -gt $b ]then echo "a 大于 b"elif [ $a -lt $b ]then echo "a 小于 b"else echo "没有符合的条件"fi
输出结果:
使用 ((...)) 作为判断语句:
a=10b=20if (( $a == $b ))then echo "a 等于 b"elif (( $a > $b ))then echo "a 大于 b"elif (( $a < $b ))then echo "a 小于 b"else echo "没有符合的条件"fi
输出结果:
if else 语句经常与 test 命令结合使用,如下所示:
num1=$[2*3]num2=$[1+5]if test $[num1] -eq $[num2]then echo '两个数字相等!'else echo '两个数字不相等!'fi
输出结果:
二、for 循环
for循环一般格式为:
for var in item1 item2 ... itemNdo command1 command2 ... commandNdone
写成一行:
for var in item1 item2 ... itemN; do command1; command2… done;
顺序输出当前列表中的数字:
for loop in 1 2 3 4 5do echo "The value is: $loop"done
输出结果:
The value is: 1The value is: 2The value is: 3The value is: 4The value is: 5
顺序输出字符串中的字符:
#!/bin/bashfor str in This is a stringdo echo $strdone
输出结果:
三、while 语句
语法格式为:
while conditiondo commanddone
以下是一个基本的 while 循环,测试条件是:如果 int 小于等于 5,那么条件返回真。int 从 1 开始,每次循环处理时,int 加 1。运行上述脚本,返回数字 1 到 5,然后终止。
#!/bin/bashint=1while(( $int<=5 ))do echo $int let "int++"done
运行脚本,输出:
输入信息被设置为变量FILM,按<Ctrl-D>结束循环。
echo '按下 <CTRL-D> 退出'echo -n '输入你最喜欢的网站名: 'while read FILMdo echo "是的!$FILM 是一个好网站"done
运行脚本:
按下 <CTRL-D> 退出输入你最喜欢的网站名:菜鸟教程是的!这 是一个好网站
1.无限循环语法格式:
或者
或者
四、until 循环
until 语法格式:
until conditiondo commanddone
使用 until 命令来输出 0 ~ 9 的数字:
#!/bin/basha=0until [ ! $a -lt 10 ]do echo $a a=`expr $a + 1`done
输出结果为:
五、case ... esac
case ... esac 语法格式:
case 值 in模式1) command1 command2 ... commandN ;;模式2) command1 command2 ... commandN ;;esac
下面的脚本提示输入 1 到 4,与每一种模式进行匹配:
echo '输入 1 到 4 之间的数字:'echo '你输入的数字为:'read aNumcase $aNum in 1) echo '你选择了 1' ;; 2) echo '你选择了 2' ;; 3) echo '你选择了 3' ;; 4) echo '你选择了 4' ;; *) echo '你没有输入 1 到 4 之间的数字' ;;esac
输入不同的内容,会有不同的结果,例如:
输入 1 到 4 之间的数字:你输入的数字为:3你选择了 3
下面的脚本匹配字符串:
#!/bin/shsite="zu"case "$site" in "zu") echo "教程" ;; "google") echo "Google 搜索" ;; "taobao") echo "淘宝网" ;;esac
输出结果为:
六、跳出循环
1.break 命令
#!/bin/bashwhile :do echo -n "输入 1 到 5 之间的数字:" read aNum case $aNum in 1|2|3|4|5) echo "你输入的数字为 $aNum!" ;; *) echo "你输入的数字不是 1 到 5 之间的! 游戏结束" break ;; esacdone
执行以上代码,输出结果为:
输入 1 到 5 之间的数字:3你输入的数字为 3!输入 1 到 5 之间的数字:7你输入的数字不是 1 到 5 之间的! 游戏结束
2.continue
#!/bin/bashwhile :do echo -n "输入 1 到 5 之间的数字: " read aNum case $aNum in 1|2|3|4|5) echo "你输入的数字为 $aNum!" ;; *) echo "你输入的数字不是 1 到 5 之间的!" continue echo "游戏结束" ;; esacdone
运行代码发现,当输入大于5的数字时,该例中的循环不会结束,语句 echo "游戏结束" 永远不会被执行。