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

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

    ~> if [ -z $FOO ]; then echo "EMPTY"; fi
    EMPTY
    ~> FOO=""
    ~> if [ -z $FOO ]; then echo "EMPTY"; fi
    EMPTY
    ~> FOO="a"
    ~> if [ -z $FOO ]; then echo "EMPTY"; fi
    ~> 
    

    -z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.

    Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.

    Alternate word:

    ~$ unset FOO
    ~$ if test ${FOO+defined}; then echo "DEFINED"; fi
    ~$ FOO=""
    ~$ if test ${FOO+defined}; then echo "DEFINED"; fi
    DEFINED
    

    Default value:

    ~$ FOO=""
    ~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
    ~$ unset FOO
    ~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
    UNDEFINED
    

    Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.

提交回复
热议问题