vinodkone vinodkone - 22 days ago 6
Bash Question

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"

Answer
#!/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".