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?
To find out if a bash variable is defined: Return true if a bash variable is unset or set to the empty string: if [ -z ${my_variable+x} ]; Also try: [ -z ${my_bash_var+y} ] && echo "\$my_bash_var not defined"
This is what I've found works best for me, taking inspiration from the other answers:
if [ -z "${varname-}" ]; then
...
varname=$(...)
fi
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With