以下内容源于C语言中文网的学习与整理,如有侵权,请告知删除。
case语句格式
case 值 in 模式1)command1command2command3;; 模式2)command1command2command3;; *)command1command2command3;; esac
- 取值后面是关键字 in。
- 取值可以为变量或常数。
- 每一模式必须以右括号结束。
- 取值符合某一模式后,该模式下的所有命令开始执行直至遇到符号“;;” 。
- “;;” 与 break 命令类似,意思是跳出整个 case 语句。
实例说明
下面的脚本提示输入1到4,与每一种模式进行匹配。
echo 'Input a number between 1 to 4' echo 'Your number is:\c' read aNum case $aNum in1) echo 'You select 1';;2) echo 'You select 2';;3) echo 'You select 3';;4) echo 'You select 4';;*) echo 'You do not select a number between 1 to 4';; esac
输入不同的内容,会有不同的结果,例如:
Input a number between 1 to 4 Your number is:3 You select 3
再举一个例子:
#!/bin/bashoption="${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 $