• 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]# 
    
  • 相关阅读:
    Vxlan基础理解
    ODPS基础
    关系型和非关系型数据库的区别?
    交换机的互连技术
    MYSQL 查看最大连接数和修改最大连接数
    Ceph添加/删除Mon(ceph.conf)
    java 线程的几个注解
    UML建模之类图
    单例模式的N种写法
    java工具jar包—Lombok
  • 原文地址:https://www.cnblogs.com/tcy1/p/13573627.html
Copyright © 2020-2023  润新知