流程控制可根據不同的情況做不同的處理,而且可重復執行指定的程序區域,在shell bash中流程控制可分為兩大類:
"選擇"和"循環"
1.選擇:if、case、select
2.循環:for、while、until、select
命令結束狀態返回值:
在shell中命令執行狀態返回值分兩種,成功和失敗,0表示成功,非0表示失敗
條件測試就是根據指定命令的狀態返回值來選擇執行相應命令
一、if條件判斷:
分三種:
單分支if
雙分支if
多分支if
單分支if:
if 條件判斷; then
命令區域
fi
如果測試條件為真,則執行命令區中中所定義的代碼
[root@CentOS6 ~]# cat if.sh #!/bin/bash # if id root &> /dev/null; then echo "root user exists." fi [root@CentOS6 ~]# bash if.sh root user exists. [root@CentOS6 ~]#
雙分支if:
if 條件判斷 ;then
命令區域1
else
命令區域2
fi
如果條件判斷為真,則執行命令區域1中的代碼,否則執行命令區域2的代碼
[root@CentOS6 ~]# cat if.sh #!/bin/bash # if id rootsdf &> /dev/null; then echo "root user exists." else echo "rootsdf user not exists." fi [root@CentOS6 ~]# bash if.sh rootsdf user not exists. [root@CentOS6 ~]#
多分支if:
if 條件判斷1 ;then
命令1
elif 條件判斷2 ;then
命令2
…
else
命令3
fi
如果條件判斷1為真,則執行命令1,如果為假,判斷條件2是否為真,如果為真,則執行命令2,否則執行命令3,elif條件可以有多個
if [ $1 -gt $2 ];then echo "$1" elif [ $1 -lt $2 ];then echo "$2" else echo "相等" fi [root@CentOS6 ~]# bash if.sh 5 3 5 [root@CentOS6 ~]# bash if.sh 6 3 6 [root@CentOS6 ~]# bash if.sh 3 3 相等 [root@CentOS6 ~]#
二、條件判斷:case語句
如果我們進行的條件測試多了起來,使用if和elif語法會顯得很啰嗦,這時我們來使用case就比較簡單了
case語法結構:
case $VAR in
PAT1)
命令1
;;
PAT2)
命令2
;;
PAT3)
命令3
…
*)
命令
esac
注意:case支持glob通配符:
*:匹配任意長度任意字符
?:匹配任意單個字符
[]:范圍內任意單個字符
a|b:a或b
[root@CentOS6 ~]# cat if.sh #!/bin/bash # case $1 in start) echo "start" ;; stop) echo "stop" ;; restart) echo "restart" ;; *) echo "error" ;; esac [root@CentOS6 ~]# bash if.sh start start [root@CentOS6 ~]# bash if.sh stop stop [root@CentOS6 ~]# bash if.sh restart restart [root@CentOS6 ~]# bash if.sh ressdfsdf error [root@CentOS6 ~]#
三、select語句:主要用于創建菜單供用戶選擇
語法格式:
select 變量名 in 列表
do
循環體
done
按數字排列的菜單項顯示在標準錯誤上,并顯示PS3提示符,來提示用戶輸入內容
用戶輸入菜單列表中的某個數字,執行相應的命令,用戶輸入的內容江北保存在變量REPLY當中
select是個死循環,因此需要使用流程控制語句來控制循環體,例如:break 退出循環
select一般結合case語句使用
[root@CentOS6 ~]# cat select.sh #!/bin/bash # PS3="Your choice: " select i in one two do case $i in one) echo "$i" echo "您輸入的是$REPLY" ;; two) echo "$i" echo "您輸入的是$REPLY" ;; *) echo "Error" break ;; esac done [root@CentOS6 ~]# bash select.sh 1) one 2) two Your choice: 1 one 您輸入的是1 Your choice: 2 two 您輸入的是2 Your choice: 3 Error [root@CentOS6 ~]#
菜單列表省略,此時使用位置參數當做列表
read命令:把用戶輸入的內容保存在一個或多個變量中
-p:指定提示符
-t #:指定超時時間
[root@CentOS6 ~]# read -p "Please enter a string: " STRING Please enter a string: zhairuixiang [root@CentOS6 ~]# echo $STRING zhairuixiang [root@CentOS6 ~]#
原創文章,作者:zhai796898,如若轉載,請注明出處:http://www.www58058.com/39455