I know that set -u
will fail the script if there are any unbound variables referenced, but in my bash script, I'm checking to see if a certain variable is unset within an if statement before I attempt to do something with it, like so:
if [[ -z "${SOME_VARIABLE}" ]] ; then
echo '$SOME_VARIABLE' is not set
else
do_stuff_with_SOME_VARIABLE
fi
However, if I try to run the above with set -eu
in my prelude, I get the following error, which seems a bit counterintuitive given what I'm trying to do:
-bash: SOME_VARIABLE: unbound variable
[Process completed]
As you can see, I'm not actually trying to use $SOME_VARIABLE
when it's unset, so what I'd like to know is if there is some way to fail the script when I'm actually trying to use unset variables (like passing them as arguments or applying string manipulations to them) but not when I'm merely checking to see if they're unset?
You could use an expansion:
if [ -z "${SOME_VARIABLE:-}" ]; then
echo '$SOME_VARIABLE' is not set
else
do_stuff_with_SOME_VARIABLE
fi
This expands $SOME_VARIABLE
to null. Read more about parameter substitution here (see the section on ${parameter:-default}
near the top)
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