case word in [ [(] pattern [| pattern]…) command-list ;;]… esac
一個 [ [(] pattern [| pattern]…) command-list ;;] 稱為一個 clause,因此
case word in 與 esac 之間可以有多個 clause,底下範例假設 clause 數量大於0。
範例:
case word in
[(] pattern [| pattern]…) command-list ;;
[(] pattern [| pattern]…) command-list ;;
....
esac
[(] 可以不加,所以可以簡化成如下形式
範例:
case word in
pattern [| pattern]…) command-list ;;
pattern [| pattern]…) command-list ;;
....
esac
如果一個 clause 只有一個 pattern,則可以簡化成如下形式
範例:
case word in
pattern ) command-list ;;
pattern ) command-list ;;
....
esac
如果有 clause 有兩個 pattern,可以寫成如下第一個 clause 的型式
範例:
case word in
pattern | pattern ) command-list ;;
pattern ) command-list ;;
....
esac
;; 可以替換成底下兩種,結果不同
1. ;& 如果此 clause 的 pattern 發生 match,則下一個 clause 的 command-list 也會被執行。
2. ;;& 如果此 clause 的 pattern 發生 match,則會往下找出所有 match 的 clause,並執行對應的 command-list。
底下範例,當輸入 one 或 two 則會連 three 那行 clause 的 command-list 也執行。當輸入 four 則會往下找所有的 clause,最後發現 *) 這個 clause 也 match,因此執行對應的 command-list。
範例:
#!/bin/sh
read -p "Please input a number in English (ex: one):"
var1=$REPLY
case $var1 in
one | two ) echo "one | two) \$var1 = $var1 ;&" ;&
three ) echo "three ) \$var1 = $var1 ;;" ;;
four ) echo "four ) \$var1 = $var1 ;;&" ;;&
five ) echo "five ) \$var1 = $var1 ;;" ;;
* ) echo "*) \$var1 = $var1 ;;" ;;
esac
結果:
[william@william-fedora test]$ ./case.sh
Please input a number in English (ex: one):one
one | two) $var1 = one ;&
three ) $var1 = one ;;
[william@william-fedora test]$ ./case.sh
Please input a number in English (ex: one):two
one | two) $var1 = two ;&
three ) $var1 = two ;;
[william@william-fedora test]$ ./case.sh
Please input a number in English (ex: one):three
three ) $var1 = three ;;
[william@william-fedora test]$ ./case.sh
Please input a number in English (ex: one):four
four ) $var1 = four ;;&
*) $var1 = four ;;
[william@william-fedora test]$ ./case.sh
Please input a number in English (ex: one):five
five ) $var1 = five ;;
[william@william-fedora test]$ ./case.sh
Please input a number in English (ex: one):six
沒有留言:
張貼留言