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

后端 未结 12 2192
没有蜡笔的小新
没有蜡笔的小新 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:11

    https://stackoverflow.com/a/9824943/14731 contains a better answer (one that is more readable and works with set -o nounset enabled). It works roughly like this:

    if [ -n "${VAR-}" ]; then
        echo "VAR is set and is not empty"
    elif [ "${VAR+DEFINED_BUT_EMPTY}" = "DEFINED_BUT_EMPTY" ]; then
        echo "VAR is set, but empty"
    else
        echo "VAR is not set"
    fi
    

提交回复
热议问题