第八章 流程控制之case语句
1 语法
case 变量 in模式1)代码1;;模式2)代码2;;模式3)代码3;;*)无匹配后命令序列esac
2 案例
2.1 案例1 猜数字
[root@xujun1270 ~]# cat case-1.sh#!/bin/bashread -p "qing shu ru shu zi:" numcase "$num" in1)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 2esac
2.2 案例2 根据水果的不同,打印出对应的颜色
[root@xujun1270 ~]# cat case-2.sh#!/bin/bashRED_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.apple2.pear3.banana4.cherry=================EOF}menuread -p "pls select color:" numcase $num in1)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/functionspidfile=/application/nginx/logs/nginx.pidstart_nginx (){if [ -f $pidfile ];thenecho "nginx is running"else/application/nginx/sbin/nginx &>/dev/nullaction "nginx is started" /bin/truefi}stop_nginx (){if [ -f $pidfile ];then/application/nginx/sbin/nginx -s stop &>/dev/nullaction "nginx is stopped" /bin/trueelseaction "nginx is stopped" /bin/falsefi}reload_nginx (){if [ -f $pidfile ];then/application/nginx/sbin/nginx -s reload &>/dev/nullaction "nginx is reloaded" /bin/trueelseecho "cat't open $pidfile,no such file or directory"fi}case $1 instart)start_nginxRETVAL=$?;;stop)stop_nginxRETVAL=$?;;restart)stop_nginxsleep 3start_nginxRETVAL=$?;;reload)reload_nginxRETVAL=$?;;*)echo "$0 {start|stop|restart}"exit 1esacexit $RETVAL
3 case语句小结
1、case语句就相当于多分支的if语句,但是case语句优势更规范、易读
2、case语句适合变量的值少,且为固定的数字或字符串集合
3、系统服务启动脚本一般都是用case语句
