shell條件判斷
1. if條件判斷if條件判斷: if [ 條件 ]; then do something fi 多個條件: && 代表AND || 代表OR 多重判斷: if [ 條件 ];then do something elif [ 條件2 ]; then //do something else //do someshing fi
#!/bin/bashread -p "Please input (Y/N) : " ynif [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then echo "Yes!"elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then echo "No!"else echo "Input Error"fiexit 0
查看運行結果
[work@www sh]$ sh hello.sh Please input (Y/N) : yYes![work@www sh]$ sh hello.sh Please input (Y/N) : lInput Error[work@www sh]$
2. case判斷如果if中判斷層級比較多,建議使用case, 否則嵌套太多,代碼易讀性變差。 case的文法 case $變數名稱 in “變數1”) do something ;; 每個結尾用兩個分號 “變數2”) do something ;; *) 最後一個*代表其他值 do something ;; esac 看下面例子:
#!/bin/bashcase $1 in "one") echo "One" ;; "two") echo "Two" ;; *) echo "Usage $0 (one|two)" ;;esacexit 0
運行結果
[work@ww sh]$ sh hello.sh Usage hello.sh (one|two)[work@www sh]$ sh hello.sh oneOne[work@www sh]$
地址:http://blog.csdn.net/yonggang7/article/details/40480695