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
You can test for undefined strings in a few ways. Using the standard test conditional looks like this:
# Test for zero-length string.
[ -z "$variable" ] || variable='foo'
This will not work with set -u
, however.
Alternatively, you can use conditional assignment, which is a more Bash-like way to do this. For example:
# Assign value if variable is unset or null.
: "${variable:=foo}"
Because of the way Bash handles expansion of this expression, you can safely use this with set -u
without getting a "bash: variable: unbound variable" error.