代码(一般写法):
#!/bin/bash
echo "Is it moring? Please answer yes or no"
read timeofday
case "$timeofday" in
yes) echo "Good Morning";;
no ) echo "Good Afternoon";;
y ) echo "Good Morning";;
n ) echo "Good Afternoon";;
* ) echo "Sorry, answer not recognized";;
esac
exit 0
简明写法:
#!/bin/bash
echo "Is it moring? Please answer yes or no"
read timeofday
case "$timeofday" in
yes | y | Yes | YES ) echo "Good Morning";;
n* | N* ) echo "Good Afternoon";;
* ) echo "Sorry, answer not recognized";;
esac
exit 0
下面例子展示了另一种的书写格式,即匹配项使用 [] 括号括起来,另外也演示了在匹配行中调用函数的形式:
[Bash shell] 纯文本查看 复制代码 #!/bin/sh
function sayhw() {
echo "hello world"
}
function sayhl() {
echo "hello linux"
}
function sayhu() {
echo "hello unix"
}
echo "which do you want to?input the number."
echo "1. say hello world"
echo "2. say hello linux"
echo "3. say hello unix"
read num
case "$num" in
[1] ) (sayhw);;
[2] ) (sayhl);;
[3] ) (sayhu);;
*) echo "nothing,exit";;
esac
运行输出:[beyes@beyes shell]$ sh case.sh
which do you want to?input the number.
1. say hello world
2. say hello linux
3. say hello unix
1
hello world |