case ... esac 與其他語(yǔ)言中的 switch ... case 語(yǔ)句類似,是一種多分枝選擇結(jié)構(gòu)。
case 語(yǔ)句匹配一個(gè)值或一個(gè)模式,如果匹配成功,執(zhí)行相匹配的命令。case 語(yǔ)句格式如下:
case 值 in
模式1)
command1
command2
command3
;;
模式2)
command1
command2
command3
;;
*)
command1
command2
command3
;;
esac
case 工作方式如上所示。取值后面必須為關(guān)鍵字 in,每一模式必須以右括號(hào)結(jié)束。取值可以為變量或常數(shù)。匹配發(fā)現(xiàn)取值符合某一模式后,其間所有命令開(kāi)始執(zhí)行直至 ;;。;; 與其他語(yǔ)言中的 break 類似,意思是跳到整個(gè) case 語(yǔ)句的最后。
取值將檢測(cè)匹配的每一個(gè)模式。一旦模式匹配,則執(zhí)行完匹配模式相應(yīng)命令后不再繼續(xù)其他模式。如果無(wú)一匹配模式,使用星號(hào) * 捕獲該值,再執(zhí)行后面的命令。
下面的腳本提示輸入1到4,與每一種模式進(jìn)行匹配:
echo 'Input a number between 1 to 4'
echo 'Your number is:\c'
read aNum
case $aNum in
1) echo 'You select 1'
;;
2) echo 'You select 2'
;;
3) echo 'You select 3'
;;
4) echo 'You select 4'
;;
*) echo 'You do not select a number between 1 to 4'
;;
esac
輸入不同的內(nèi)容,會(huì)有不同的結(jié)果,例如:
Input a number between 1 to 4
Your number is:3
You select 3
再舉一個(gè)例子:
#!/bin/bash
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
運(yùn)行結(jié)果:
$./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
$