鍍金池/ 教程/ Linux/ Shell case...esac 語句
Shell 輸入/輸出重定向
Shell 循環(huán)類型
Shell是什么?
Shell 特殊變量
Shell 算術(shù)運算符示例
Shell 關(guān)系運算符示例
Shell 替代
Shell 函數(shù)
Shell 條件語句
Shell 聯(lián)機幫助
Shell 數(shù)組/Arrays
Shell 布爾運算符范例
Shell
Shell if...elif...fi 語句
Shell case...esac 語句
Shell 使用Shell變量
Shell 文件測試符例子
Shell 基本運算符
Korn Shell 運算符
Shell 字符串運算范例
Shell while 循環(huán)
Shell 引用機制
Shell if...else...fi 語句
Shell select 循環(huán)
C Shell運算符
Shell 循環(huán)控制break/continue
Shell for循環(huán)
Shell until 循環(huán)
Shell if...fi語句

Shell case...esac 語句

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

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

語法

case...esac 語句基本語法 是為了給一個表達式計算和幾種不同的語句來執(zhí)行基于表達式的值。

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

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

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

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

當語句部分執(zhí)行,命令;; 表明程序流程跳轉(zhuǎn)到結(jié)束整個 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語句是一個很好用的命令行參數(shù)如下計算:

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