Shell多分支case语句

一 语法
case语法和if...elif...else语句一样都是多分支条件语句,不过和if多分支条件语句不同的是,case语句只能判断一种条件关系,而if语句可以判断多种条件关系。
case $变量名 in
"值1")
如果变量的值等于1,则执行程序1
;;
"值2")
如果变量的值等于1,则执行程序2
;;
...省略其他分支..
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
 
二 实战
#!/bin/bash
read -p "please choose yes/no:" -t 30 cho
case $cho in
"yes")
echo "Your choose is yes"
;;
"no")
echo "Your choose is no"
;;
*)
echo "Your choose is error"
;;
esac
 
三 测试
[root@localhost shell]# ./shell7.sh
please choose yes/no:yes
Your choose is yes
[root@localhost shell]# ./shell7.sh
please choose yes/no:no
Your choose is no
[root@localhost shell]# ./shell7.sh
please choose yes/no:fd
Your choose is error
 
四 实战2
#!/bin/bash
echo "fengj : qing shuru 1"
echo "fur:qing shuru 2"
echo "buod:qing shuru 3"
 
read -t 30 -p "qing shuru xuanze" cho
case "$cho" in
"1")
echo "fengj gengni"
;;
"2")
echo "fur jiagei ni"
;;
"3")
echo "fuduo he wo zou"
;;
*)
echo "qing shuru zhengq xuanze"
;;
esac
 
五 测试2
[root@localhost shell]# ./shell8.sh
fengj : qing shuru 1
fur:qing shuru 2
buod:qing shuru 3
qing shuru xuanze2
fur jiagei ni
[root@localhost shell]# ./shell8.sh
fengj : qing shuru 1
fur:qing shuru 2
buod:qing shuru 3
qing shuru xuanze3
fuduo he wo zou
[root@localhost shell]# ./shell8.sh
fengj : qing shuru 1
fur:qing shuru 2
buod:qing shuru 3
qing shuru xuanze4
qing shuru zhengq xuanze

猜你喜欢

转载自cakin24.iteye.com/blog/2393149