Shell case...esac 語句

 可以使用多個if...elif 語句執行多分支。然而,這並不總是最佳的解決方案,尤其是當所有的分支依賴於一個單一的變數的值。

Shell支持 case...esac  語句處理正是這種情況下,它這樣做比 if...elif 語句更有效。

語法

case...esac 語句基本語法 是為了給一個運算式計算和幾種不同的語句來執行基於運算式的值。

解釋器檢查每一種情況下對運算式的值,直到找到一個匹配。如果沒有匹配,默認情況下會被使用。

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

這裏的字串字每個模式進行比較,直到找到一個匹配。執行語句匹配模式。如果沒有找到匹配,聲明退出的情況下不執行任何動作。

沒有最大數量的模式,但最小是一個。

當語句部分執行,命令;; 表明程式流程跳轉到結束整個 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

這將產生以下結果:

New Zealand is famous for kiwi.

case語句是一個很好用的命令行參數如下計算:

#!/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 

下麵是一個示例運行這個程式:

$./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
$

上一篇: Shell if...elif...fi 語句 下一篇: Shell 迴圈類型