簡書著作權歸作者所有,任何形式的轉載都請聯(lián)系作者獲得授權并注明出處。
? ? ? ?這篇文章講述一下 case 條件分支語句。在多分支條件判定的場景中,可以使用 if 條件分支語句來編寫腳本,但可能看上去不那么優(yōu)雅,這時候可以考慮使用 case 條件分支語句。
? ? ? ?為方便講述,先虛構這么一個場景:程序在和用戶交互時,程序要根據(jù)用戶的輸入在終端進行相應的輸出。
? ? ? ?當用戶輸入是 1 時,程序在終端輸出 1 ;
? ? ? ?當用戶輸入是 2 時,程序在終端輸出 2 ;
? ? ? ?當用戶輸入是 3 時,程序在終端輸出 3 ;
? ? ? ?當用戶的輸入不是 1 不是 2 也不是 3 時,程序在終端輸出 You did not enter a number between 1 and 3.
? ? ? ? 如果使用 if 條件分支語句,腳本如下:
#!/bin/bash
echo -n "Enter a number between 1 and 3 inclusive > "
read character
if [ "$character" = "1" ]; then
echo "You entered one."
elif [ "$character" = "2" ]; then
echo "You entered two."
elif [ "$character" = "3" ]; then
echo "You entered three."
else
echo "You did not enter a number between 1 and 3."
fi
? ? ? ? 上面的這種寫法完全可以實現(xiàn)我們需要的功能,但看上去 if... elif... else... 的使用次數(shù)較多,代碼顯得臃腫,這時候如果我們選擇使用 case 條件分支語句,腳本如下:
#!/bin/bash
echo -n "Enter a number between 1 and 3 inclusive > "
read character
case $character in
1 ) echo "You entered one."
;;
2 ) echo "You entered two."
;;
3 ) echo "You entered three."
;;
* ) echo "You did not enter a number between 1 and 3."
esac
? ? ? ? 這段腳本實現(xiàn)了和第一個腳本同樣的功能,但看上去清爽了很多。這就是 case 條件分支語句的作用。
? ? ? ? 接下來簡單介紹一下 case 條件分支語句的使用方法:
case word in
pattern1 ) command1 ;;
pattern2 ) command2 ;;
...
patternn ) commandn ;;
esac
? ? ? ? 腳本在執(zhí)行時會將 word 的形式與下面第 1 個到第 n 個 pattern 的模式進行匹配,如果匹配成功則執(zhí)行相應 pattern 后面的命令,并且不再嘗試與后續(xù)的 pattern 進行模式匹配。比如 word 的模式與第 2 個 pattern 的模式相匹配,那么程序?qū)?zhí)行第二個 pattern 后面的命令,這時即便 word 和第 2 個 pattern 后面的某個 pattern 相匹配,程序也不會做任何動作了。
? ? ? ? 這里有兩點需要注意:
? ? ? ?1、patterns 是 Shell 中的正則表達式,與 java 或 python 中的正則表達式是有區(qū)別的。要想知道更多關于 Shell 正則表達式的知識,可以自己搜索相關的教程;
? ? ? ?2、注意兩個分號的使用,如果只用一個分號會報錯。
? ? ? ?在知道了 case 條件分支語句的使用方法后,再來展示一個稍稍復雜點的例子:
? ? ? ?(1)當用戶輸入的是單個字母時,程序在終端輸出 You typed the letter
? ? ? ?(2)當用戶輸入的是單個數(shù)字時,程序在終端輸出 You typed the digit
? ? ? ?(3)當用戶輸入其他內(nèi)容時,程序在終端輸出 You did not type a letter or a digit
? ? ? ?實現(xiàn)該功能的腳本如下:
#!/bin/bash
echo -n "Type a digit or a letter > "
read character
case $character in
# Check for letters
[[:lower:]] | [[:upper:]] ) echo "You typed the letter"
;;
# Check for digits
[0-9] ) echo "You typed the digit"
;;
# Check for anything else
* ) echo "You did not type a letter or a digit"
esac
? ? ? ?這段腳本也很簡單,如果讀者在看這段代碼時感覺有困難,可能是看不太明白正則表達式部分。不過沒有關系,因為你只需要知道這里是在講述 case 條件分支語句的使用方法,只要知道了這些這里就達到了知識分享的目的。如果真的很想弄明白 Shell 中的正則表達式,還是那句話,可以自己搜索相關教程來學習。
相關文檔
http://linuxcommand.org/lc3_wss0110.php
上一篇:Shell Script(五):交互和算數(shù)運算
下一篇:Shell Script(七):循環(huán)(for, while, until)