可以使用多個(gè)if...elif 語句執(zhí)行多分支。然而,這并不總是最佳的解決方案,尤其是當(dāng)所有的分支依賴于一個(gè)單一的變量的值。
Shell支持 case...esac 語句處理正是這種情況下,它這樣做比 if...elif 語句更有效。
case...esac 語句基本語法 是為了給一個(gè)表達(dá)式計(jì)算和幾種不同的語句來執(zhí)行基于表達(dá)式的值。
解釋器檢查每一種情況下對(duì)表達(dá)式的值,直到找到一個(gè)匹配。如果沒有匹配,默認(rèn)情況下會(huì)被使用。
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
esac
這里的字符串字每個(gè)模式進(jìn)行比較,直到找到一個(gè)匹配。執(zhí)行語句匹配模式。如果沒有找到匹配,聲明退出的情況下不執(zhí)行任何動(dòng)作。
沒有最大數(shù)量的模式,但最小是一個(gè)。
當(dāng)語句部分執(zhí)行,命令;; 表明程序流程跳轉(zhuǎn)到結(jié)束整個(gè) case 語句。和C編程語言的 break 類似。
#!/bin/sh
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
這將產(chǎn)生以下結(jié)果:
New Zealand is famous for kiwi.
case語句是一個(gè)很好用的命令行參數(shù)如下計(jì)算:
#!/bin/sh
option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac
下面是一個(gè)示例運(yùn)行這個(gè)程序:
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$
更多建議: