zoukankan      html  css  js  c++  java
  • shell 函数返回值与字典

    shell的函数只能返回整数值,如果想让函数返回字符串可以在函数调用处为变量赋值。

    # 定义函数
    function test() { name
    =$1 echo "123213" }
    # 调用函数,执行结果赋值给变量ret ret
    =$(test "lishichao") echo $ret

    # 执行结果 [root@dev
    -test shell]# sh test.sh 123213

    最近在写一键安装脚本,一个一个判断输入参数太麻烦,所以使用shell字典匹配对应函数。

    function main(){
        if [[ $USER != "root" ]]
        then
            echo "Please use root account"
            exit
        fi
        if [[ -z $VAR ]]
        then
            echo "please input your action:pypy,nginx,redis,mysql,hall0,hall37"
            exit
        fi
    
        case $VAR in
            "pypy")
                install_pypy5
                ;;
            "nginx")
                nginx
                ;;
            "redis")
                install_redis
                ;;
            "mysql")
                install_mysql
                ;;
            "hall0")
                hall0
                ;;
            "hall37")
                hall37
                ;;
            *)
                echo "please  input your action:pypy,nginx,redis,mysql,hall0,hall37"
                ;;
        esac
    }
    
    main
    使用case判断输入参数
    function install_php() {
        echo "安装php7"
        exit 0
    }
    
    function install_filebeat() {
        echo "安装filebeat"
        exit 0
    }
    
    function install_rabbitmq() {
        echo "安装rabbitmq"
        exit 0
    }
    
    function install_logstash() {
        echo "安装logstash"
        exit 0
    }
    
    
    declare -A dic
    dic=([php]=install_php [logstash]=install_logstash [filebeat]=install_filebeat)
    
    VAR=$1
    for key in $(echo ${!dic[*]})
    do
        if [[ $VAR == $key ]];then
           ${dic[$VAR]} 
           echo "$key"
        fi
    done
    
    echo "$(pwd)/$0 {pypy | nginx | redis | mysql | hall0 | hall37 | rabbitmq | logstash | filebeat}"

    执行结果:

    [root@dev-test shell]# sh test.sh 
    /opt/shell/test.sh {pypy | nginx | redis | mysql | hall0 | hall37 | rabbitmq | logstash | filebeat}
    [root@dev
    -test shell]# sh test.sh logstash 安装logstash [root@dev-test shell]# sh test.sh filebeat 安装filebeat
  • 相关阅读:
    dns解析后ping的居然不是自己的ip
    Ubuntu修改默认使用的bash
    安装 libbpg
    libnccl安装
    安装opencv
    tcpdump使用
    jQuery类操作
    jQuery对象和DOM对象的相互转换
    jQuery入口函数
    什么是外边距重叠?重叠的结果是什么?
  • 原文地址:https://www.cnblogs.com/root0/p/11896818.html
Copyright © 2011-2022 走看看