How to Determine if a Bash Variable Is Empty


If you need to check if a bash variable is empty, or unset, then you can use the following code:

if [ -z "${VAR}" ];

The above code will check if a variable called VAR is set, or empty.

What does this mean?

Unset means that the variable has not been set.

Empty means that the variable is set with an empty value of "".

What is the inverse of -z?

The inverse of -z is -n.

if [ -n "$VAR" ];

A short solution to get the variable value

VALUE="${1?"Usage: $0 value"}"

Test if a variable is specifically unset

if [[ -z ${VAR+x} ]]

Test the various possibilities

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

This means:

                        +-------+-------+-----------+
                VAR is: | unset | empty | non-empty |
+-----------------------+-------+-------+-----------+
| [ -z "${VAR}" ]       | true  | true  | false     |
| [ -z "${VAR+set}" ]   | true  | false | false     |
| [ -z "${VAR-unset}" ] | false | true  | false     |
| [ -n "${VAR}" ]       | false | false | true      |
| [ -n "${VAR+set}" ]   | false | true  | true      |
| [ -n "${VAR-unset}" ] | true  | false | true      |
+-----------------------+-------+-------+-----------+