case … esac 與其他語言中的 switch … case 語句類似,是一種多分枝選擇結構。
case 語句匹配一個值或一個模式,如果匹配成功,執行相匹配的命令。case語句格式如下:
case 值 in
模式1)
command1
command2
command3
;;
模式2)
command1
command2
command3
;;
*)
command1
command2
command3
;;
esac
注意:
- 取值後面必須爲關鍵字 in
- 每一模式必須以右括號結束
- 取值可以爲變量或常數
- 匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;
- ;; 與其他語言中的 break 類似,意思是跳到整個 case 語句的最後。
- 如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。
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
使用read從標準輸入讀取並賦值給aNum,然後case esac判斷輸入並執行相關語句。
#!/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
option變量等於命令行第一個參數,命令行第2參數爲名稱,通過第一個參數判斷是一個文件還是一個目錄。
$./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