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"
How you can check the variable is set or not in bash is shown in this tutorial. '-v' or '-z' option is used to check the variable is set or unset. The above Boolean expression will return true if the variable is set and returns false if the variable is not set or empty.
#!/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".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With