bash assign default value

前端 未结 4 1695
一生所求
一生所求 2020-12-22 16:55

${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of pa

4条回答
  •  一向
    一向 (楼主)
    2020-12-22 17:36

    You can also use := construct to assign and decide on action in one step. Consider following example:

    # Example of setting default server and reporting it's status
    
    server=$1
    if [[ ${server:=localhost} =~ [a-z] ]]      # 'localhost' assigned here to $server
    then    echo "server is localhost"          # echo is triggered since letters were found in $server
    else
            echo "server was set" # numbers were passed
    fi
    

    If $1 is not empty, localhost will be assigned to server in the if condition field, trigger match and report match result. In this way you can assign on the fly and trigger appropriate action.

提交回复
热议问题