您可以使用多个 if ... elif 语句执行多路分支。但是,这并不总是最好的解决方案,尤其是当所有分支都取决于单个变量的值时。
Shell支持 case ... esac 语句,该语句恰好可以处理这种情况,并且比if ... elif语句重复执行更有效。
Case-esac - 语法
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语句将不执行任何操作而退出。
没有最大数量的模式,但最小数量为1。
当语句部分执行时,命令;;指示程序流应跳到整个case语句的末尾。这类似于C编程语言中的中断。
Case-esac - 例子
#!/bin/shFRUIT="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/shoption="{option} in -f) FILE="FILE" ;; -d) DIR="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 $