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
Advanced bash scripting guide, 10.2. Parameter Substitution:
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.