在看選擇判斷結構之前,請務必先看一下數值比較與文件測試
if....else...
#!/bin/bash
#文件名:test.sh
score=66
# //格式一
if [ $score -lt 60 ]
then
echo "60以下"
elif [ $score -lt 70 ]
then
echo "60-70"
else
echo "70以上"
fi
# 格式二
if [ $score -lt 60 ];then
echo "60以下"
elif [ $score -lt 70 ];then
echo "60-70"
else
echo "70以上"
fi
運行結果:
ubuntu@ubuntu:~$ ./test.sh 60-70 60-70 ubuntu@ubuntu:~$
支持嵌套if...else....也和其他語言一樣,需要注意的是,每一個選擇判斷分支都要結束(使用if的反寫fi)。
#!/bin/bash
#文件名:test.sh
score=66
if [ $score -lt 60 ];then
if [ $score -gt 55 ];then
echo "55-60"
elif [ $score -lt 55 ];then
echo "小於55"
fi
elif [ $score -lt 70 ];then
if [ $score -gt 65 ];then
echo "65-70"
elif [ $score -lt 60 ];then
echo "60-65"
fi
else
echo "70以上"
fi
運行結果:
ubuntu@ubuntu:~$ ./test.sh 65-70 ubuntu@ubuntu:~$
需要注意的是,上面的每一行都是一條命令,如果想要將某幾行寫在一行,那么要在每一行之后加分號,分號必不可少。
掌握以上的內容后,看一下這個例子:
#!/bin/bash
#文件名:test.sh
num=6
if [ $num%2 -eq 0 ]
then
echo "yes"
else
echo "no"
fi
如果你認為這個腳本可以正常運行,會輸出yes的話,那你肯定是被其他語言中的if判斷給影響了,不信看一下結果:
ubuntu@ubuntu:~$ ./test.sh ./test.sh: line 6: [: 6%2: integer expression expected no ubuntu@ubuntu:~$
錯誤信息很好理解,數學運算的表達式在這里計算的方法或者存在的形式是不對的,那么要怎么才行呢?
也許你會說將數學計算的表達式使用$(( ))括起來就行了,比如下面:
#!/bin/bash
#文件名:test.sh
num=6
if [ $[ $num % 2 ] -eq 0 ]
#或者下面兩種方法
#if [ $(( $num % 2 )) -eq 0 ]
#if [ `expr $num % 2` -eq 0 ]
then
echo "yes"
else
echo "no"
fi
運行:
ubuntu@ubuntu:~$ ./test.sh yes ubuntu@ubuntu:~$
推薦使用$[ command ] 來進行整數計算
case
以case開始,以esac結尾(case反着寫),每一個switch不用謝break,默認滿足其中一個就會break。
#!/bin/bash
#文件名:test.sh
read -p "please input number: " week
case $week in
1 | 2 | 3 | 4 | 5 )
echo "I'm working";;
6 | 7)
echo "I'm playing";;
*) #類似去其他語言中的default
echo "I'm dying";;
esac
運行:
ubuntu@ubuntu:~$ ./test.sh please input number: 6 I'm playing ubuntu@ubuntu:~$ ./test.sh please input number: 1 I'm working ubuntu@ubuntu:~$ ./test.sh please input number:8 I'm dying ubuntu@ubuntu:~$
其中每一個匹配的部分可以是常量或者變量,需要注意的是匹配的部分后面必須有右括號,然后每一種情況都要使用兩個分號分隔。 從上之下開始匹配,一旦匹配,則執行相應的命令,不再進行后續的匹配判斷。
*)表示前面所有情況都不匹配時,才執行下面的操作,一般用在最后,和其他語言中的default相同。
另外case的匹配模式中,如果有多個匹配之后的操作都相同時,可以使用|來將多個匹配模式寫在一起,表示或者,只要滿足其中一個 模式,就執行這條語句。
在指定條件的地方,還可以是正則表達式
當然,還有一種情況也可以達到這種類似的效果,如下:
#!/bin/bash
#文件名:test.sh
read -p "please input the key: " key
case $key in
[a-z] | [A-Z])
#注意上面一條命令中間使用了|
echo "alpha";;
[0-9])
echo "number";;
*)
echo "other key"
esac
運行:
ubuntu@ubuntu:~$ ./test.sh please input the key: a alpha ubuntu@ubuntu:~$ ./test.sh please input the key: 2 number ubuntu@ubuntu:~$ ./test.sh please input the key: ! other key ubuntu@ubuntu:~$
