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

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

    another option: the "list array indices" expansion:

    $ unset foo
    $ foo=
    $ echo ${!foo[*]}
    0
    $ foo=bar
    $ echo ${!foo[*]}
    0
    $ foo=(bar baz)
    $ echo ${!foo[*]}
    0 1
    

    the only time this expands to the empty string is when foo is unset, so you can check it with the string conditional:

    $ unset foo
    $ [[ ${!foo[*]} ]]; echo $?
    1
    $ foo=
    $ [[ ${!foo[*]} ]]; echo $?
    0
    $ foo=bar
    $ [[ ${!foo[*]} ]]; echo $?
    0
    $ foo=(bar baz)
    $ [[ ${!foo[*]} ]]; echo $?
    0
    

    should be available in any bash version >= 3.0

提交回复
热议问题