if-then 語句 if commandthen commands fi if-then 的語法和我們熟悉的其他高級編程語言有些差別,以C++為例,if 后面一般是條件判斷表達式,通過表達式返回 True or False,來決定運行或者不運行接下來的命令,而Shell 中的 if-then 不同,if 語句會執(zhí)行其后的命令,如果命令的退出碼為 '0', 則執(zhí)行 then 后的邏輯,如果退出碼非 '0',則不執(zhí)行。'fi' 表示 if-then 邏輯語句的結束。 if-then-else 語句 if commandthen commandselse commandsfi if-then-else 語句與if-then 相同,只是當if 后免得command 返回碼為非 '0'時,會執(zhí)行else 語句。 if-then-elif-then 語句 if command1then commandselif command2then commandselsethen commandsfi 原理其實和if-then-else沒有區(qū)別,只是增加了邏輯分支的判斷匹配。 test 命令 test condition #test命令的格式 if-then 系列的命令中,if語句不能直接判斷condition,而只能通過命令的返回碼來作為條件判斷依據(jù),這有些時候并不便利,而且和我們熟悉的其他高級語言中的 if-else 語法不同。test 命令可以幫助我們轉變shell 中的 if-then 結構語法為我們熟悉的語法。標準的結構是: if test conditionthen commandsfi bash shell中也提供了另一中方法來實現(xiàn) test 相同的結果, 將condition 用方括號[]括起來 if [ condition ] #方括號和condition之間要有空格then commandsfi 數(shù)值比較 結合上面的內容,舉一個例子說明: 輸出結果為: the value of 10 is greater than value of 5value of 5 is equal to 5 注:bash shell中只能比較整數(shù)。 字符串比較 因為字符串比較中,直接用了數(shù)學符號,而bash中會將大于號和小于號理解為重定向符號(之前的文章中有介紹重定向的含義和用法),所以做字符串比較是需要對大于號和小于號做轉義,轉義方式為在 '<' or '>' 之前加 '\'. 直接上例子 輸出結果為:'hello is less than world' 文件比較 復合條件測試 [ condition1 ] && [ condition2 ] [ condition1 ] | | [ condition2 ] 條件判斷高級用法 1.使用雙圓括號, 且雙圓括號內的 '<' or '>' 號不需要轉義。 (( expression )) 雙圓括號可以使用的表達式更多,如下 2.使用雙方括號, 注:并不是所有的bash都支持雙方括號語法。 [[ expression ]] case 命令 shell 中的 case 命令和其他高級語言的用法是一樣的,都是為了解決 if-then-elif 太多的情況,可以是代碼更清晰。case 語句的格式為 case variable in pattern1 | pattern2) command1;;pattern3) command2;;*) default commands;;esac 直接上例子: |
|