For Shell script, sometimes, we want to find out whether a variable is set or unset. The problem is that there is no easy way to distinguish between:
To identify them, we use an unique conditions approach using the variable expansion substitution. The idea is that, when a variable is unset, the entire variable expands into nothing; Otherwise, it is substituted with a character. Then, you just need to check against this single character existence to know whether a variable is set or unset.
The easiest way is to use the variable +x expansion. Here is an example:
#!/bin/dashif [ ! -z ${variable+x} ]; then echo "variable is set"fiNOTE
"", which is a valid empty string.Similarly, to check the unset, we use the -z condition. Here is an example:#!/bin/dash
if [ -z ${variable+x} ]; then echo "variable is unset"fiNOTE
"", which is a valid empty string.That's all for checking a variable is unset or empty.