Test if a variable is set in bash when using "set -o nounset"
The following code exits with a unbound variable error. How to fix this, while still using the set -o
nounset option?
#!/bin/bash
set -o nounset
if [ ! -z ${WHATEVER} ];
then echo "yo"
fi
echo "whatever"
Solution 1:
#!/bin/bash
set -o nounset
VALUE=${WHATEVER:-}
if [ ! -z ${VALUE} ];
then echo "yo"
fi
echo "whatever"
In this case, VALUE
ends up being an empty string if WHATEVER
is not set. We're using the {parameter:-word}
expansion, which you can look up in man bash
under "Parameter Expansion".
Solution 2:
You need to quote the variables if you want to get the result you expect:
check() {
if [ -n "${WHATEVER-}" ]
then
echo 'not empty'
elif [ "${WHATEVER+defined}" = defined ]
then
echo 'empty but defined'
else
echo 'unset'
fi
}
Test:
$ unset WHATEVER
$ check
unset
$ WHATEVER=
$ check
empty but defined
$ WHATEVER=' '
$ check
not empty
Solution 3:
How about a oneliner?
[ -z "${VAR:-}" ] && echo "VAR is not set or is empty" || echo "VAR is set to $VAR"
-z
checks both for empty or unset variable