Check if a variable is set in Bash

Checking if a variable is set is easy in Bash; however, there are two common scenarios:

  1. Checking if a variable is empty or unset
  2. Checking if a variable is unset

Checking if a variable is empty or unset

Firstly, a simple test may be used to determine if a variable’s value is empty or if it’s unset.

1
2
3
if [[ -z "$var" ]]; then
    echo "it's empty or unset"
fi

OR

1
2
3
4
var=""
if [[ -z "$var" ]]; then
    echo "it's empty or unset"
fi

Output:

1
it's empty or unset

The -z tests if the string length is zero.

Checking if a variable is unset

Checking if a variable is unset requires a different implementation.

1
2
3
if [[ -z "${var+set}" ]]; then
    echo "it's unset"
fi

Output:

1
it's unset

However, if the var value is set to an empty value:

1
2
3
4
var=
if [[ -z "${var+set}" ]]; then
    echo "it's unset"
fi

OR

1
2
3
4
var=""
if [[ -z "${var+set}" ]]; then
    echo "it's unset"
fi

the output will not print anything.

The ${var+set} works because of parameter expansion:

If parameter is unset or null, null shall be substituted; otherwise, the expansion of word (or an empty string if word is omitted) shall be substituted.