Shell case条件语句的应用实践

Shell case条件语句的应用实践

罗小黑
2021-06-21 / 0 评论 / 44 阅读 / 正在检测是否收录...
广告
温馨提示:
本文最后更新于2021年06月24日,已超过157天没有更新,若内容或图片失效,请留言反馈。

语法格式

case "变量" in
    值1)
        指令1
        ;;
    值2)
        指令2
        ;;
    *)
        指令3
        ;;
esac

示例

#!/bin/bash
read -p "请输入[1-3]数字:" a
case "$a" in
    1)
      echo "1"
      ;;
    2)
      echo "2"
      ;;
    3)
      echo "3"
      ;;
    *)
    echo "请输入[1-3]"
esac

示例2

#!/bin/bash
[ $# -ne 1 ] && echo "Uasge: $0 {start|stop|restart|relad|status}" && exit

function start(){
ps aux | grep [n]ginx | grep -q master
    if [ $? -eq 0 ]; then
        echo "nginx启动成功"
    else
        /usr/local/nginx/sbin/nginx &>/dev/null
        if [ $? -eq 0 ]; then
            echo "nginx启动成功"
        else
            echo "nginx启动失败"
        fi
    fi
}
function stop(){
ps aux | grep [n]ginx | grep -q master
    if [ $? -eq 0 ]; then
        /usr/local/nginx/sbin/nginx -s stop >/dev/null
        sleep 2
        ps aux | grep [n]ginx | grep -q master
        if [ $? -ne 0 ]; then
            echo "niginx关闭成功"
        else
            echo "nginx关闭失败"
        fi
      echo "nginx关闭成功"
    fi
}
case "$1" in
start)
    start
;;
stop)
    stop
;;
restart)
# ps aux | grep [n]ginx | grep -q master
#    if [ $? -eq 0 ];then
#        /usr/local/nginx/sbin/nginx -s stop &>/dev/null
#        sleep 2
#        /usr/local/nginx/sbin/mginx &>/dev/null
#        if [ $? -eq 0 ]; then
#            echo "nginx 重启成功"
#        else
#            echo "nginx重启失败"
#        fi
#    else
#        /usr/local/nginx/sbin/nginx &>/dev/null
#        if [ $? -eq 0 ];then
#            echo "nginx重启成功"
#        else
#            echo "nginx重启失败"
#        fi
#   fi
   stop
   start
;;
reload)
   stop
   start
;;
status)
    ps aux | grep [n]ginx | grep -q master
    if [ $? -eq 0 ]; then
        echo "nginx is up"
    else
        echo "nginx is down"
    fi
;;
*)
 echo "Uasge: $0 {start|stop|restart|relad|status}"
exit
esac
0

打赏

评论 (0)

取消