您可以使用多个 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语句将不执行任何操作而退出。
没有最大数量的模式,但最小数量为1。
当语句部分执行时,命令;;指示程序流应跳到整个case语句的末尾。这类似于C编程语言中的中断。
链接:https://www.learnfk.comhttps://www.learnfk.com/linux/linux-case-esac-statement.html
来源:LearnFk无涯教程网
#!/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 $
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)