Bash: How to set a variable from argument, and with a default value

后端 未结 3 1413
耶瑟儿~
耶瑟儿~ 2021-02-05 01:17

It is pretty clear that with shell scripting this sort of thing can be accomplished in a huge number of ways (more than most programming languages) because of all the different

3条回答
  •  無奈伤痛
    2021-02-05 02:17

    I use a simple helper function to make such assignments look cleaner. The function below accepts any number of arguments, but returns the first one that's not the empty string.

    default_value() {
        # Return the first non-empty argument
        while [[ "$1" == "" ]] && [[ "$#" -gt "0" ]]; do
            shift
        done
        echo $1
    }
    x=$(default_value "$1" 0)
    

提交回复
热议问题