一、Case基本介绍
- 1.什么是case
case和 if 多分⽀条件判断 语句差不多,或者说 是⼀样的,只不过case要⽐ if 要更加的规 范,更加的⽅便。 - 2.case使用场景
case需要实现定义好规则,然后根据⽤户传⼊ 的参数,进⾏匹配,加载不同的匹配规则内 容。
⽐如: nginx启停脚本。 ( 启动 | 停⽌ | 重启 等等操作 )
写好 启动、停⽌、重启等三个预案,然后根据⽤户的 选择匹配对应的预案进行即可 - 3.case的执行流程
进⾏挨个匹配,匹配成功则直接执⾏,后续的预案就不在进⾏匹配了 。
如果所有的都没有匹配成功,那么⾃动进⾏⼀个 接收所有的预案中。 - 4.case基础语法
case $1 in
start)
command
;;
stop)
command
;;
restart)
command
;;
*)
command
esac
例子:
#!/bin/bash
cat <<eof
****************
** 1. backup**
** 2. copy**
** 3. quit**
****************
eof
read -p "请输⼊你想执⾏的操作: " OP
case $OP in
1|backup|b|back)
echo "Backup Is Done..."
;;
2)
echo "Copy IS Done...."
;;
3)
exit
;;
*)
echo "USAGE: sh $0 [ 1 | 2 | 3 ]"
exit
esac
二、Case job
- 1.使用case实现nginx服务启动脚本
. /etc/init.d/functions
# start | stop | restart |
case $1 in
start)
#1.判断是否已启动过
ngx_status=$(systemctl status nginx | grep Active | awk '{print $2}')
#2.进⾏字符串的⽐较(不是整数⽐较、也不是正则⽐较、也不是⽂件⽐较)
if [ "$ngx_status" == "inactive" ];then
systemctl start nginx
action "Nginx启动成功..." /bin/true
elif [ "$ngx_status" == "active" ];then
action "Nginx启动成功..." /bin/true
exit
fi
;;
stop)
ngx_status=$(systemctl status nginx | grep Active | awk'{print $2}')
if [ "$ngx_status" == "inactive" ];then
action "Nginx停⽌成功..." /bin/true
elif [ "$ngx_status" == "active" ];then
systemctl stop nginx
action "Nginx停⽌成功..." /bin/true
fi
;;
*)
echo "USAGE: sh $0 [ start | stop | restart ] "
esac
- 使用case实现nginx状态监控脚本。
1.先得将7种状态展示出来。
2.将每种状态分别 提取。
case $1 in
Active|active)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status | awk '/Active/ {print $NF}'
;;
accept)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status |awk 'NR==3 {print $1}'
;;
handled)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status |awk 'NR==3 {print $2}'
;;
requests)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status |awk 'NR==3 {print $3}'
;;
reading)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status |awk 'NR==4 {print $2}'
;;
writing)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status |awk 'NR==4 {print $4}'
;;
waiting)
curl -s -HHost:nginx.oldxu.com http://127.0.0.1:80/nginx_status |awk 'NR==4 {print $NF}'
;;
*)
echo "USAGE: sh $0 [ active | accept | handled | requests | reading | writing | waiting ]"
esac