Skip to content

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}" ];
Code language: Bash (bash)

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" ];
Code language: Bash (bash)

A short solution to get the variable value

VALUE="${1?"Usage: $0 value"}"
Code language: Bash (bash)

Test if a variable is specifically unset

if [[ -z ${VAR+x} ]]
Code language: Bash (bash)

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
Code language: Bash (bash)

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 | +-----------------------+-------+-------+-----------+
Code language: plaintext (plaintext)

See also  How to Dockerize a Flask App
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x