I just discovered set -u in bash and it helped me find several previously unseen bugs. But I also have a scenario where I need to test if a variable is defined before computing some default value. The best I have come up with for this is:
if [ "${variable-undefined}" == undefined ]; then
variable="$(...)"
fi
which works (as long as the variable doesn’t have the string value undefined). I was wondering if there was a better way?
What Doesn’t Work: Test for Zero-Length Strings
You can test for undefined strings in a few ways. Using the standard test conditional looks like this:
This will not work with
set -u, however.What Works: Conditional Assignment
Alternatively, you can use conditional assignment, which is a more Bash-like way to do this. For example:
Because of the way Bash handles expansion of this expression, you can safely use this with
set -uwithout getting a “bash: variable: unbound variable” error.