條件判斷: case語句
在shell編程中,對于多分支判斷,用if 雖然也可以實現,但有些時候,寫起來很麻煩,也不容易代碼理解。這個時候,可以考慮case。
case 變量引用 in
PAT1)
分支1
;;
PAT2)
分支2
;;
…
*)
默認分支
;;
esac
case語句結構特點如下:
case行尾必須為單詞“in”,每一個模式必須以右括號“)”結束。
雙分號“;;”表示命令序列結束。
匹配模式中可是使用方括號表示一個連續的范圍,如[0-9];使用豎杠符號“|”表示或。
“|”分割多個模式,相當于or
最后的“*)”表示默認模式,當使用前面的各種模式均無法匹配該變量時,將執行“*)”后的命令序列。
腳本代碼
[root@localhost bin]# cat chatype.sh #!/bin/bash # Description: Determine the type of input character read -p "Please enter a character: " char case $char in [A-Z]) echo "Input is capital letters." ;; [a-z]) echo "Input is lowercase letter." ;; [0-9]) echo "Input is digital." ;; *) echo "Input is other char." ;; esac
執行結果
[root@localhost bin]# chatype.sh Please enter a character: a Input is lowercase letter. [root@localhost bin]# chatype.sh Please enter a character: N Input is capital letters. [root@localhost bin]# chatype.sh Please enter a character: 3 Input is digital. [root@localhost bin]# chatype.sh Please enter a character: % Input is other char. [root@localhost bin]# chatype.sh Please enter a character: ! Input is other char.
原創文章,作者:cyh5217,如若轉載,請注明出處:http://www.www58058.com/36036