Unix / Linux 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
;;
*)
Default condition to be executed
;;
esac
此处将字符串单词与每个模式进行比较,直到找到匹配项。 执行匹配模式后的语句。 如果未找到匹配项,则 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 $

