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

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

    Advanced bash scripting guide, 10.2. Parameter Substitution:

    • ${var+blahblah}: if var is defined, 'blahblah' is substituted for the expression, else null is substituted
    • ${var-blahblah}: if var is defined, it is itself substituted, else 'blahblah' is substituted
    • ${var?blahblah}: if var is defined, it is substituted, else the function exists with 'blahblah' as an error message.


    to base your program logic on whether the variable $mystr is defined or not, you can do the following:

    isdefined=0
    ${mystr+ export isdefined=1}
    

    now, if isdefined=0 then the variable was undefined, if isdefined=1 the variable was defined

    This way of checking variables is better than the above answer because it is more elegant, readable, and if your bash shell was configured to error on the use of undefined variables (set -u), the script will terminate prematurely.


    Other useful stuff:

    to have a default value of 7 assigned to $mystr if it was undefined, and leave it intact otherwise:

    mystr=${mystr- 7}
    

    to print an error message and exit the function if the variable is undefined:

    : ${mystr? not defined}
    

    Beware here that I used ':' so as not to have the contents of $mystr executed as a command in case it is defined.

提交回复
热议问题