11.1.【case语句语法】
case word in
pattern1)
list1
;;
pattern2)
list2
;;
…
patternN)
listN
;;
esac
• 格式还可以写成:
• case word in
• pattern1) list1;;
• …
• patternN) listN;;
• esac
11.2.【case语句语法说明】
字符串变量word与从pattern1到patternN的所有模式一一比较。
当找到一个匹配模式后就执行跟在匹配模式后的list
当一个list执行完了,专用命令;;表明流应该跳转到case语句的最后。
;;类似C语言中的break指令。
如果找不到匹配的模式,case语句就不做任何动作。
11.3.【case语句练习1】
FRUIT=orange
case “$FRUIT” in
apple) echo “Apple is red.”;;
banana) echo “banana is green.”;;
orange) echo “orange is orange.”;;
esac
• case语句的流程如下:
• 1.变量FRUIT包含字符串orange
• 2.字符串orange和第一个模式apple比较。由于
不匹配,程序转向下一个模式
• 3.字符串orange和第一个模式banana比较。由于
不匹配,程序转向下一个模式
• 4.字符串orange和最后的模式kiwi比较它们匹配
于是产生下面的信息:
• orange is orange.
11.4.【case语句练习2】
#!/bin/bash
echo 'Please Enter Your choice:'
read age
case "$age" in
20)
echo $age is too young ;;
30)
echo $age is so good ;;
40)
echo $age is little old ;;
*)
echo "Tell me other choice ,please ";;
esac
#!/bin/bash
echo 'Please Enter Your choice:'
read age
case "$age" in
20)
echo $age is too young ;;
30)
echo $age is so good ;;
40)
echo $age is little old ;;
*)
echo "Tell me other choice ,please ";;
esac
11.5.【case语句练习3】
• FRUIT=orange
• case “$FRUIT” in
• apple) echo “Apple is red.”;;
• banana) echo “banana is green.”;;
• orange) echo “orange is orange.”;;
• esac
• case语句的流程如下:
• 1.变量FRUIT包含字符串orange
• 2.字符串orange和第一个模式apple比较。由于
不匹配,程序转向下一个模式
• 3.字符串orange和第一个模式banana比较。由于
不匹配,程序转向下一个模式
• 4.字符串orange和最后的模式kiwi比较它们匹配
于是产生下面的信息:
• orange is orange.
11.6.【case语句练习4】
#!/bin/bash
echo 'Please Enter Your choice:'
read age
case "$age" in
20)
echo $age is too young ;;
30)
echo $age is so good ;;
40)
echo $age is little old ;;
*)
echo "Tell me other choice ,please ";;
esac
11.7.【case语句课后练习5】
练习:建立脚本case.sh,当执行时,要求我们在键盘输入适当的值(one|two|three),
当输入正确时并打印,当输入错误时会提示你,应该输入正确的值。
#!/bin/bash
echo "press your chioce one,two,three"
read number
case $number in
one)
echo "your choice is one"
;;
two)
echo "your choice is two"
;;
three)
echo "your choice is three"
;;
*)
echo "Usage {one|two|three}"
esac
---------------------------------------------------