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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM