shell流程控制之多分支case语句

1. case与if…elif…else

它们都是多分支条件句,不同的是,case语句只能判断一种条件关系,而if语句可以判断多种关系

2. 格式

case $变量名 in
"值1") 如果变量的值等于值1,则执行程序1;;
"值2") 如果变量的值等于值2,则执行程序2;;
......
*) 如果变量的值都不是以上的值,则执行此程序;;
esac

3. 练习1:判断用户输入

脚本

#!/bin/bash
#判断用户输入

read -p "please choose yes/no:" -t 30 cho

case $cho in
        "yes") echo "your choose is yes";;
        "no") echo "your chosse is no";;
        *) echo "please input yes|no";;
esac

测试脚本

[root@catyuan ~]# chmod 755 case1.sh 
[root@catyuan ~]# ./case1.sh 
please choose yes/no:yes
your choose is yes
[root@catyuan ~]# ./case1.sh 
please choose yes/no:no
your chosse is no
[root@catyuan ~]# ./case1.sh 
please choose yes/no:dv
please input yes|no

4. 练习2

脚本

[root@catyuan ~]# vim case2.sh
#!/bin/bash
#选择你想去的城市

echo "shanghai:please input 1"
echo "xi'an:please input 2"
echo "beijing:please input 3"

read -t 30 -p "please input your choose:" cho

case $cho in
        "1") echo "shanghai";;
        "2") echo "xi'an";;
        "3") echo "beijing";;
        *) echo "please input 1|2|3"
esac

测试脚本

[root@catyuan ~]# chmod 755 case2.sh 
[root@catyuan ~]# ./case2.sh 
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:1
shanghai
[root@catyuan ~]# ./case2.sh 
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:2
xi'an
[root@catyuan ~]# ./case2.sh 
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:3
beijing
[root@catyuan ~]# ./case2.sh 
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:5
please input 1|2|3

你可能感兴趣的:(shell脚本)