第八章 流程控制之case语句
1 语法
case 变量 in
模式1)
代码1
;;
模式2)
代码2
;;
模式3)
代码3
;;
*)
无匹配后命令序列
esac
2 案例
2.1 案例1 猜数字
[root@xujun1270 ~]# cat case-1.sh
#!/bin/bash
read -p "qing shu ru shu zi:" num
case "$num" in
1)
echo "zhe ge shu zi shi 1"
;;
2)
echo "zhe ge shu zi shi 2"
;;
3)
echo "zhe ge shu zi shi 3"
;;
*)
echo "bi xu you shu zi"
exit 2
esac
2.2 案例2 根据水果的不同,打印出对应的颜色
[root@xujun1270 ~]# cat case-2.sh
#!/bin/bash
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
menu(){
cat <<EOF
==================
1.apple
2.pear
3.banana
4.cherry
=================
EOF
}
menu
read -p "pls select color:" num
case $num in
1)
echo -e "${RED_COLOR}apple${RES}"
;;
2)
echo -e "${GREEN_COLOR}pear${RES}"
;;
3)
echo -e "${YELLOW_COLOR}banana${RES}"
;;
4)
echo -e "${BLUE_COLOR}cherry${RES}"
;;
*)
echo "$0 be {1|2|3|4}"
esac
2.3 案例3 nginx启动脚本
[root@xujun1270 init.d]# cat nginx.sh
#!/bin/bash
#chkconfig: 2345 40 80
#description:starts,stop and saves iptables firewall
. /etc/init.d/functions
pidfile=/application/nginx/logs/nginx.pid
start_nginx (){
if [ -f $pidfile ];then
echo "nginx is running"
else
/application/nginx/sbin/nginx &>/dev/null
action "nginx is started" /bin/true
fi
}
stop_nginx (){
if [ -f $pidfile ];then
/application/nginx/sbin/nginx -s stop &>/dev/null
action "nginx is stopped" /bin/true
else
action "nginx is stopped" /bin/false
fi
}
reload_nginx (){
if [ -f $pidfile ];then
/application/nginx/sbin/nginx -s reload &>/dev/null
action "nginx is reloaded" /bin/true
else
echo "cat't open $pidfile,no such file or directory"
fi
}
case $1 in
start)
start_nginx
RETVAL=$?
;;
stop)
stop_nginx
RETVAL=$?
;;
restart)
stop_nginx
sleep 3
start_nginx
RETVAL=$?
;;
reload)
reload_nginx
RETVAL=$?
;;
*)
echo "$0 {start|stop|restart}"
exit 1
esac
exit $RETVAL
3 case语句小结
1、case语句就相当于多分支的if语句,但是case语句优势更规范、易读
2、case语句适合变量的值少,且为固定的数字或字符串集合
3、系统服务启动脚本一般都是用case语句