bash test the various possibilities

The following are examples of how you can test the various possibilities, and it works in bash or any POSIX-compatible shell:

if [ -z “${VAR}” ]; then
echo “VAR is unset or set to the empty string”
fi
if [ -z “${VAR+set}” ]; then
echo “VAR is unset”
fi
if [ -z “${VAR-unset}” ]; then
echo “VAR is set to the empty string”
fi
if [ -n “${VAR}” ]; then
echo “VAR is set to a non-empty string”
fi
if [ -n “${VAR+set}” ]; then
echo “VAR is set, possibly to the empty string”
fi
if [ -n “${VAR-unset}” ]; then
echo “VAR is either unset or set to a non-empty string”
fi

A variable in bash (and any POSIX-compatible shell) can be in one of three states:

unset
set to the empty string
set to a non-empty string
Most of the time you only need to know if a variable is set to a non-empty string, but occasionally it’s important to distinguish between unset and set to the empty string.

Leave a Reply

Your email address will not be published. Required fields are marked *