How to tell if a string is not defined in a Bash shell script

后端 未结 12 2166
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 04:42

If I want to check for the null string I would do

[ -z $mystr ]

but what if I want to check whether the variable has been defined at all? O

12条回答
  •  再見小時候
    2020-12-02 05:08

    Here is what I think is a much clearer way to check if a variable is defined:

    var_defined() {
        local var_name=$1
        set | grep "^${var_name}=" 1>/dev/null
        return $?
    }
    

    Use it as follows:

    if var_defined foo; then
        echo "foo is defined"
    else
        echo "foo is not defined"
    fi
    

提交回复
热议问题