Check if a variable is set in Bash
Checking if a variable is set is easy in Bash; however, there are two common scenarios:
- Checking if a variable is empty or unset
- 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.
1if [[ -z "$var" ]]; then
2 echo "it's empty or unset"
3fi
OR
1var=""
2if [[ -z "$var" ]]; then
3 echo "it's empty or unset"
4fi
Output:
1it'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.
1if [[ -z "${var+set}" ]]; then
2 echo "it's unset"
3fi
Output:
1it's unset
However, if the var
value is set to an empty value:
1var=
2if [[ -z "${var+set}" ]]; then
3 echo "it's unset"
4fi
OR
1var=""
2if [[ -z "${var+set}" ]]; then
3 echo "it's unset"
4fi
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.