- Unix/Linux 初學者教程
- Unix/Linux - 首頁
- Unix/Linux - 什麼是Linux?
- Unix/Linux - 入門指南
- Unix/Linux - 檔案管理
- Unix/Linux - 目錄
- Unix/Linux - 檔案許可權
- Unix/Linux - 環境變數
- Unix/Linux - 基本工具
- Unix/Linux - 管道與過濾器
- Unix/Linux - 程序
- Unix/Linux - 通訊
- Unix/Linux - vi 編輯器
- Unix/Linux Shell 程式設計
- Unix/Linux - Shell 指令碼
- Unix/Linux - 什麼是Shell?
- Unix/Linux - 使用變數
- Unix/Linux - 特殊變數
- Unix/Linux - 使用陣列
- Unix/Linux - 基本運算子
- Unix/Linux - 決策語句
- Unix/Linux - Shell 迴圈
- Unix/Linux - 迴圈控制
- Unix/Linux - Shell 替換
- Unix/Linux - 引號機制
- Unix/Linux - I/O 重定向
- Unix/Linux - Shell 函式
- Unix/Linux - 手冊頁幫助
- 高階 Unix/Linux
- Unix/Linux - 標準 I/O 流
- Unix/Linux - 檔案連結
- Unix/Linux - 正則表示式
- Unix/Linux - 檔案系統基礎
- Unix/Linux - 使用者管理
- Unix/Linux - 系統性能
- Unix/Linux - 系統日誌
- Unix/Linux - 訊號和陷阱
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
廣告