zoukankan      html  css  js  c++  java
  • SHELL使用--case语句

    case语句

    语法介绍

    case $变量名 in
    值1)
        命令1
        命令2
        命令3
        ;;
    值2)
        命令1
        命令2
        命令3
        ;;
    值3)
        命令1
        命令2
        命令3
        ;;
    *)
        命令1
        命令2
        命令3
    esac
    
    
    # 类似
    if [ $变量名 == 值1 ];then
        命令1
        命令2
        命令3
    elif [ $变量名 == 值2 ];then
        命令1
        命令2
        命令3
    elif [ $变量名 == 值3 ];then
        命令1
        命令2
        命令3
    else
        命令1
        命令2
        命令3
    fi
    

    示例1

    • 测试用户身份
    #!/bin/bash
    
    read -p "请输入你的用户名: " name
    case $name in
    "root")
        echo "超级管理员"
        ;;
    "egon")
        echo "VIP用户"
        ;;
    "tom")
        echo "SVIP用户"
        ;;
    *)
        echo "其他用户"
    esac
    

    示例2

    • nginx管理脚本
    • 根据传参判断是对服务进行什么操作,针对每种操作的结果进行分析,处理
    [root@db01 day04]# cat nginx.sh 
    #!/bin/bash
    . /etc/init.d/functions
    case $1 in
    "start")
        netstat -an|grep 'LISTEN'|grep '80' &>/dev/null
        if [ $? -eq 0 ];then
            action "nginx 已经是启动状态了哦~" true
        else
            systemctl start nginx &>/dev/null
           if [ $? -eq 0 ];then
              action "nginx启动成功" true
           else
              action "nginx start failed" false
           fi
        fi
    ;;
    
    "stop")
        systemctl stop nginx &>/dev/null
        if [ $? -eq 0 ];then
            action "nginx已经停止服务" true
        else
            action "nginx无法正常停止..." false
        fi
    ;;
    
    "status")
        netstat -an|grep 'LISTEN'|grep '80'
        if [ $? -eq 0 ];then
             action "nginx is up" true
        else
             action "nginx is down" false
        fi
    ;;
    
    "reload")
        systemctl reload nginx &>/dev/null
        if [ $? -eq 0 ];then
            action "nginx已经重新加载成功" true
        else 
            action "nginx重新加载失败" false
        fi
    ;;
    
    *)
        echo "您的语法有误请输入正确语法"
    esac
    
    

    PS小细节

    # 引入functions 函数,可以配合使用true和flase对输出结果颜色显示
    
    [root@egon day04]# . /etc/init.d/functions 
    [root@egon day04]# action "nginx start ok" true
    nginx start ok                                             [  OK  ]
    [root@egon day04]# action "nginx start ok" false
    nginx start ok                                             [FAILED]
    [root@egon day04]# 
    
  • 相关阅读:
    JVM系列五:JVM监测&工具[整理中]
    Washing Text Animation
    Cloth
    藤条生长为字母的动画
    音频驱动曲线
    Wood Chipping Text Animation
    融化的文字
    流体文本动画
    Blender Tutorial
    UV纹理+修改器:VertexWeightEdit+修改器:Mask遮罩
  • 原文地址:https://www.cnblogs.com/tcy1/p/13573627.html
Copyright © 2011-2022 走看看