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?
You can use:
at the start of your script to throw an error when using undefined variables.
set -u
is the more general option, but as pointed out in other answers' comments, there are problems writing idiomatic shell scripts withset -u
in play. An alternative is to create parameter expansions that yield an error when a specific variable isn't set.This error will cause a non-interactive shell to exit. This gives you a quick way to guarantee an error condition won't allow control flow to continue with an undefined value. The spec does not require an interactive shell to exit, although it's worth noting that even in an interactive shell, bash will return from a function call if this error occurs in a function.