Unix/Linux Shell - case...esac 語句



您可以使用多個if...elif語句來執行多路分支。但是,這並非總是最佳解決方案,尤其是在所有分支都依賴於單個變數的值時。

Shell 支援case...esac語句,它可以精確處理這種情況,並且比重複使用if...elif語句效率更高。

語法

case...esac語句的基本語法是給出一個表示式進行評估,並根據表示式的值執行幾個不同的語句。

直譯器會將每個case與表示式的值進行比較,直到找到匹配項。如果沒有匹配項,則將使用預設條件。

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
      ;;
   *)
     Default condition to be executed
     ;;
esac

這裡將字串word與每個模式進行比較,直到找到匹配項。匹配模式後的語句將執行。如果找不到匹配項,則case語句將退出而不執行任何操作。

模式的數量沒有最大限制,但最小值為一個。

當語句部分執行時,命令;;表示程式流程應該跳轉到整個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
$
unix-decision-making.htm
廣告
© . All rights reserved.