Check Unset Variable
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:
- a variable is set but the value is null or empty
- an unset variable
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.
Check for Set
Check for Set
The easiest way is to use the variable +x expansion. Here is an example:
#!/bin/dash
if [ ! -z ${variable+x} ]; then
echo "variable is set"
fi
NOTE
- Take important note that the variable is not quoted. We want the variable to expand to nothing, not
""
, which is a valid empty string.
Check for Unset
Check for Unset
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"
fi
NOTE
- Take important note that the variable is not quoted. We want the variable to expand to nothing, not
""
, which is a valid empty string.
That's all for checking a variable is unset or empty.