和if/elif/else结构一样,case结构同样可用于多分支选择语句,常用来根据表达式的值选择要执行的语句,该命令的一般格式为:
case Variable in
value1)
command
…
command;;
value2)
command
…
command;;
…
valueN)
command
…
command;;
*)
command
…
command;;
esac
case $变量名称in <==关键字为 case ,还有变数前有钱字号
“第一个变数内容”) <==每个变数内容建议用双引号括起来,关键字则为小括号 )
程式段
;; <==每个类别结尾使用两个连续的分号来处理!
“第二个变数内容”)
程式段
;;
*) <==最后一个变数内容都会用 * 來代表所有其他值
不包含第一个变数内容与第二个变数内容的其它程式执行段
;;
esac <==最终 case 结尾
vim case_exam1.sh
#case_exam1.sh:
#!/bin/bash
echo "Please Input a mouth(0-12): "
read month
case "$month" in
1) echo "The month is January!";;
2) echo "The month is February!";;
3) echo "The month is March!";;
4) echo "The month is April!";;
5) echo "The month is May!";;
6) echo "The month is June!";;
7) echo "The month is July!";;
8) echo "The month is August!";;
9) echo "The month is September!";;
10) echo "The month is October!";;
11) echo "The month is November!";;
12) echo "The month is December!";;
*) echo "The month is not in (0-12).";;
esac
echo "The 'case' command ends"
++++++++++++++++++++++++++++++++++++++++++
vim case_exam2.sh
#case_exam2.sh:
#!/bin/bash
echo "Please Input a score_type(A-E): "
read score_type
case "$score_type" in
A)
echo "The range of score is from 90 to 100 !";;
B)
echo "The range of score is from 80 to 89 !";;
C)
echo "The range of score is from 70 to 79 !";;
D)
echo "The range of score is from 60 to 69 !";;
E)
echo "The range of score is from 0 to 59 !";;
*)
echo "What you input is wrong !";;
esac