shell脚本—case用法

shell脚本—case用法

1.什么是case?

case语句和if类似,也是用来判断的,只不过当判断的条件较多时,使用case语句会if更加方便

2.case使用场景

在生产环境中,我们总会遇到一个问题需要根据不同的状况来执行不同的预案,那么我们要处理这样的问题首先要根据可能出现的情况写出对应预案,然后根据选择来加载不同的预案。

比如服务器启停脚本,我们首先要写好启动,停止,重启的预案,然后根据不用的选择加载不同的预案

3.case语法

case 变量 in
条件 1)
      执行代码块1
      ;;
条件 2)
      执行代码块2
      ;;
条件 3)
      执行代码块3
      ;;
*)
      无匹配后命令序列
 esac
#示例1:输入1备份,输入2copy,输入3退出,输入其他的提醒不要乱输入
[root@manage case]# cat case01.sh 
#!/bin/bash
cat <<eof
****************
** 1. backup  **
** 2. copy    **
** 3. quit    **
****************
eof
read -p "请输入要执行的编号:[ 1 | 2 | 3 ]:" Action
case $Action in 
        1|backup|BACKUP)
               echo "backup....."
               ;;
        2|copy|COPY)
               echo "copy........"
               ;;
        3|quit|QUIT)
               exit
               ;;
        *)
               echo "USAGE:$0 请不要乱输入...."
     
esac

#示例2:输入1.输出5.5,输入2输出7.0,输入3输出7.5版本,输入4退出,输入5提示不要乱输入
[root@manage case]# cat case02.sh 
#!/bin/bash
clear
cat <<EOF
=====================================
1) Installed PHP 5.5 
2) Installed PHP 7.0
3) Installed PHP 7.3 
4) quit
=====================================
EOF
read -p "请输入你要安装的版本[ 1 | 2 | 3 | 4 ]: " Action

case $Action in
     1)
       echo "Installed PHP 5.5"
       ;;
     2)
       echo "Installed PHP 6.5"
       ;;
     3)
       echo "Installed PHP 7.5"
       ;;
     4)
       exit
       ;;
     *)
       echo "AUSAGE: $0 请不要乱输入...."
       exit

esac

#需求3:用case实现nginx启停脚本
[root@manage case]# cat case03.sh 
#!/bin/bash
source /etc/init.d/functions
nginx_pid=/var/run/nginx.pid

case $1 in
	start)
		if [ -f $nginx_pid ];then
			if [ -s $nginx_pid ];then
				action "Nginx 已经启动" /bin/false
			else
				rm -f $nginx_pid
				systemctl start nginx &>/dev/null
				if [ $? -eq 0 ];then
					action "Nginx启动成功" /bin/true
				else
					action "Nginx启动失败" /bin/false
				fi
			fi
		else
			systemctl start nginx &>/dev/null
			if [ $? -eq 0 ];then
				action "Nginx启动成功" /bin/true
			else
				action "Nginx启动失败" /bin/false
			fi
		fi
		;;
	stop)
		if [ -f $nginx_pid ];then
			systemctl stop nginx && \
			rm -f $nginx_pid
			action "Nginx is stopped" /bin/true
		else
			echo "[error] open() "$nginx_pid" failed (2: No such file or directory)"
		fi
		;;
	status)
		if [ -f $nginx_pid ];then
			echo "nginx (pid  $(cat $nginx_pid)) is running..."
		else
			echo "nginx is stopped"
		fi
		;;
	reload)
		#1.nginx没有启动直接报错
		#2.nginx启动了,先检查配置文件语法
			#如果nginx语法没问题,则reload
			#如何nginx语法有问题
				#提示用户是否进入对应的错误行数修改 [ y | n ]
					# y 进入修改
					# n 退出操作
		if [ -f $nginx_pid ];then
			nginx -t -c /etc/nginx/nginx.conf &>nginx.err
			rc=$?

			if [ $rc -eq 0 ];then
				action "Nginx is Reloaded" /bin/true
			else
				ngx_conf=$(cat nginx.err |awk -F "[ :]" 'NR==1 {print $(NF-1)}')
				ngx_line=$(cat nginx.err |awk -F "[ :]" 'NR==1 {print $NF}')
				read -p "是否进入 ${ngx_conf} 配置文件的 ${ngx_line} 行修改: [ y | n ] " tt
				case $tt in
					y)
						vim $ngx_conf +${ngx_line}
						;;
					n)
						exit 1
				esac
			fi

		else
			action "Nginx 没有启动" /bin/false
		fi
		;;
	*)
		echo "USAGE:  $0 {start|stop|status|restart}"
		exit 1
esac


[root@manage case]# sh case04.sh status
nginx (pid  ) is running...
[root@manage case]# sh case04.sh stop
Nginx is stopped                                           [  OK  ]
[root@manage case]# sh case04.sh reload
Nginx 没有启动                                             [FAILED]
[root@manage case]# sh case04.sh start
Nginx启动成功                                              [  OK  ]
[root@manage case]# sh case04.sh reload
Nginx is Reloaded                                          [  OK  ]

#需求4:使用case实现nginx状态监控脚本。 stub_status
sh nginx_status.sh
USAGE nginx_status.sh { Active | accepts | handled | requests | Reading  | Writing  |Waiting }
	1.nginx开启状态监控
	[root@manager case]# cat /etc/nginx/conf.d/test.conf 
	server {

		listen 80;
		server_name test.ttt.com;

		location / {
			index index.html;
		}

		location /nginx_status {
			stub_status;
		}
	}
	2.awk取值		curl -H Host:test.ttt.com http://127.0.0.1:80/nginx_status
			
	3.case
	
	
[root@manage case]# cat case05.sh 
#!/bin/bash
HostName=test.ttt.com
Nginx_status_file=nginx.status
Nginx_Status_Path=nginx_status

curl -sH Host:${HostName} http://127.0.0.1/${Nginx_Status_Path} >${Nginx_status_file}
case $1 in
        active)
              echo $(( $(awk '/Active connections: / {print $NF}' ${Nginx_status_file}) -1 ))
              ;;
        accepts)
              echo $(( $(awk 'NR==3 {print $1}' ${Nginx_status_file}) -1 ))
              ;;
        handled)
              echo $(( $(awk 'NR==3 {print $2}' ${Nginx_status_file}) -1 ))
              ;;
        requests)
              echo $(( $(awk 'NR==3 {print $3}' ${Nginx_status_file}) -1 ))
              ;;
        Reading)
              echo $(( $(awk 'NR==4 {print $2}' ${Nginx_status_file}) -1 ))
              ;;
        Writing)
              echo $(( $(awk 'NR==4 {print $4}' ${Nginx_status_file}) -1 ))
              ;;
        Waiting)
              echo $(( $(awk 'NR==4 {print $6}' ${Nginx_status_file}) -1 ))
              ;;
        *)
              echo "USAGE: $0 { active | accepts | handled | requests | Reading  | Writing  | Waiting }"
              exit 1
esac

[root@manage case]# sh case05.sh active
0
[root@manage case]# sh case05.sh accepts
10
[root@manage case]# sh case05.sh handled
11
[root@manage case]# sh case05.sh requests
12

#需求5:case实现php状态监控脚本  php_status
[root@manage case]# yum install php-fpm php pho -y
[root@manage case]# vim /etc/php-fpm.d/www.conf 
pm.status_path = /php_status
[root@manage case]# systemctl start php-fpm

[root@manage case]# cat /etc/nginx/conf.d/test.conf 
server {
       listen 80;
        server_name test.ttt.com;

        location / {
              index index.html;
 }
        location /nginx_status {
                 stub_status;
          }
        location /php_status {
                 fastcgi_pass 127.0.0.1:9000;
                 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                 include fastcgi_params;
 }
}

[root@manage case]# systemctl restart nginx  php-fpms

[root@manage case]# cat case06.sh 
#!/bin/bash
case $1 in
        accepted)
         echo "$(( $(awk '/accepted conn/ {print $NF}' php.status)))"
        ;;
        listen)
         echo "$(( $(awk 'NR==6 {print $NF}' php.status)))"
        ;;
        idle)
         echo "$(( $(awk '/idle/ {print $NF}' php.status)))"
        ;;
        active)
         echo "$(( $(awk '/^active/ {print $NF}' php.status)))"
        ;;
        total)
         echo "$(( $(awk '/total/ {print $NF}' php.status)))"
        ;;
        slow)
         echo "$(( $(awk '/slow/ {print $NF}' php.status)))"
        ;;
        *)
           echo "[ESAUG: accepted  | listen | idle | active | total |  | slow ]"
           exit 1
        
esac

#需求6:编写脚本,根据用户输入的服务名称查询该服务的状态,并让用户选择启动、关闭、重启、保持不变并输出改服务器以启动、关闭、重启、保持不变

1.接收用户输入的服务名称   $1
2.根据用户传入的$1 查询服务对应的状态
3.针对已启动的,重启或关闭
4.针对未启动,启动或停止

[root@manage case]# cat case07.sh 
#!/bin/bash
#判断用户传入的参数
if [ $# -ne 1 ];then
        echo "USAGE: server name [nginx | httpd | vsftpd | php-fpm ]"
        exit
fi

#当前执行脚本的是否为超级管理员
if [ $UID -ne 0 ];then
         echo "\"$USER\" $0 不是超级管理员"

         exit
fi
systemctl status $1 &>/dev/null

if [ $? -eq 4 ];then
           echo "Unit $1 could not be found"

else
         #字符串比对
         system_status=$(systemctl status $1 | grep Active | awk '{print $2}')
         if [ $system_status == "active" ];then
                     read -p "$1 已启动,可以选择[ restart | stop ]:" Action
                      case $Action in
                           restart)
                              systemctl restart $1 >/dev/null
                              echo "$1重启成功....."
                           ;;
                           stop)
                              systemctl stop $1 >/dev/null
                               echo "$1 停止成功....."
                           ;;
                           *)
                            exit 1
                      esac
         elif [ $system_status == "inactive" ];then
                     read -p "$1 未启动,可以选择 [ start | quit ]:" Action
                     case $Action in
                          start)
                                systemctl start $1
                                echo "$1启动成功"
                                ;;
                           quit)
                                echo "退出"
                                exit
                                ;;
                            *)
                                exit
                     esac
         fi
fi

[root@manage case]# sh +x case07.sh nginx
nginx 未启动,可以选择 [ start | quit ]:start
nginx启动成功
[root@manage case]# sh +x case07.sh nginx
nginx 已启动,可以选择[ restart | stop ]:stop
nginx 停止成功.....


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值