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

1
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.

1
if [ -n "$VAR" ];

A short solution to get the variable value

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

Test if a variable is specifically unset

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

Test the various possibilities

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
                        +-------+-------+-----------+
                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      |
+-----------------------+-------+-------+-----------+