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]# 
    
  • 相关阅读:
    SVN Windows环境搭建,简洁演示
    SVN-linux配置
    链接文本在a标签内标签里也可以用driver.find_element_by_link_text
    selenium python自动化简明演示
    关键字中mysql数据库查询条件带中文无结果解决办法
    python 最短路径
    python 难度分割
    c语言实现一个高铁乘客管理系统
    Linux(Ubuntu)系统安装图文教程
    字符串排序
  • 原文地址:https://www.cnblogs.com/tcy1/p/13573627.html
Copyright © 2011-2022 走看看