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
  • 相关阅读:
    vi 或 vim 常用命令(简单够用了)
    linux 常用命令
    ssh连接远程linux服务器
    tomcat优化系列:修改运行内存
    html学习笔记二
    html学习笔记一
    我的subLime的快捷键
    CentOS tomcat 安装与自启动
    CentOS 安装jdk-8u111-linux-x64.tar.gz方法
    CentOS 6 默认启动进入 图形或命令窗口
  • 原文地址:https://www.cnblogs.com/root0/p/11896818.html
Copyright © 2011-2022 走看看