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

后端 未结 3 543
梦毁少年i
梦毁少年i 2021-02-05 01:11

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:08

    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)
    

提交回复
热议问题