Unbound Variable errors in Bash scripts

It is well appreciated that when set -u is active Bash will report an error if an unbound variable is referenced, e.g.:

set -u
echo $nosuchvar

returns an error:

script.sh: line 2: nosuchvar: unbound variable

The solution is usually to check if/where the variables are set. However, when using a common array idiom, apparently set variables can be unbound. Consider following:

set -u
shopt -s nullglob

vv=/tmp/nosuchfile*

vv=($vv)

echo $vv

Here nullglob is set so that a glob with no matches will return null. This script also returns an unbound variable error! The reason is that redefinition of vv as an empty array variable clears the existing binding without making a new one.

The solution is to bracket the use of vv with a check of its existence, for example:

set -u
shopt -s nullglob

vv=/tmp/nosuchfile*

vv=($vv)

if [ -n "${vv:-}" ]; then
    echo $vv
fi

See the "Use Default Values" sub-section of "Parameter Expansion" of the bash man page.

Try this out on REPL.IT