Shell 腳本的 if-else/case 用法

if-then 語句

if command
then
commands
fi

if-then 的語法和我們熟悉的其他高級編程語言有些差別,以C++為例,if 後面一般是條件判斷表達式,通過表達式返回 True or False,來決定運行或者不運行接下來的命令,而Shell 中的 if-then 不同,if 語句會執行其後的命令,如果命令的退出碼為 '0', 則執行 then 後的邏輯,如果退出碼非 '0',則不執行。'fi' 表示 if-then 邏輯語句的結束。

if-then-else 語句

if command
then
commands
else
commands
fi

if-then-else 語句與if-then 相同,只是當if 後免得command 返回碼為非 '0'時,會執行else 語句。

if-then-elif-then 語句

if command1
then
commands
elif command2
then
commands
else
then
commands
fi

原理其實和if-then-else沒有區別,只是增加了邏輯分支的判斷匹配。

test 命令

test condition #test命令的格式

if-then 系列的命令中,if語句不能直接判斷condition,而只能通過命令的返回碼來作為條件判斷依據,這有些時候並不便利,而且和我們熟悉的其他高級語言中的 if-else 語法不同。test 命令可以幫助我們轉變shell 中的 if-then 結構語法為我們熟悉的語法。標準的結構是:

if test condition
then
commands
fi

bash shell中也提供了另一中方法來實現 test 相同的結果, 將condition 用方括號[]括起來

if [ condition ] #方括號和condition之間要有空格
then
commands
fi

數值比較

Shell 腳本的 if-else/case 用法

結合上面的內容,舉一個例子說明:

Shell 腳本的 if-else/case 用法

輸出結果為:

the value of 10 is greater than value of 5
value of 5 is equal to 5

注:bash shell中只能比較整數。

字符串比較

Shell 腳本的 if-else/case 用法

因為字符串比較中,直接用了數學符號,而bash中會將大於號和小於號理解為重定向符號(之前的文章中有介紹重定向的含義和用法),所以做字符串比較是需要對大於號和小於號做轉義,轉義方式為在 '' 之前加 "". 直接上例子

Shell 腳本的 if-else/case 用法

輸出結果為:"hello is less than world"

文件比較

Shell 腳本的 if-else/case 用法

複合條件測試

[ condition1 ] && [ condition2 ] 
[ condition1 ] | | [ condition2 ]

條件判斷高級用法

1.使用雙圓括號, 且雙圓括號內的 '' 號不需要轉義。

(( expression ))

雙圓括號可以使用的表達式更多,如下

Shell 腳本的 if-else/case 用法

2.使用雙方括號, 注:並不是所有的bash都支持雙方括號語法。

[[ expression ]]

case 命令

shell 中的 case 命令和其他高級語言的用法是一樣的,都是為了解決 if-then-elif 太多的情況,可以是代碼更清晰。case 語句的格式為

case variable in 
pattern1 | pattern2) command1;;
pattern3) command2;;
*) default commands;;
esac

直接上例子:

Shell 腳本的 if-else/case 用法


分享到:


相關文章: