Please note: there are many questions about how to test a single shell variable on this site. This question is about testing a script for any undefined variable.
You can use an undefined variable in bash without seeing any error at execution:
#!/bin/bash
echo ${UNDEF_FILE}
ls -l ${UNDEF_FILE}
exit 0
I've found this very error prone. If I want to change the name of a variable in a large script, or remove that variable, all the previous stale references will cause errors in the script. Sometimes this is not obvious to debug or you find out when it's too late.
Why is this allowed? Is there any way to flag undefined variables?
[[ $var ]] & { echo "Doing something with $var"; }
, for instance, will break withset -u
: Unlikeset -e
(which makes only failures which aren't checked or used as conditionals into failures),set -u
makes every reference to an undefined variable an error.[[ $var ]]
DOES NOT WORK ifset -u
is in use, not that it's an available mechanism to check whether a single variable is unset. Likewise for[ -n "$var" ]
,[ -z "$var" ]
, etc; you need a different set of idioms if usingset -u
.