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

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

    not to shed this bike even further, but wanted to add

    shopt -s -o nounset
    

    is something you could add to the top of a script, which will error if variables aren't declared anywhere in the script. The message you'd see is unbound variable, but as others mention it won't catch an empty string or null value. To make sure any individual value isn't empty, we can test a variable as it's expanded with ${mystr:?}, also known as dollar sign expansion, which would error with parameter null or not set.

提交回复
热议问题