How to find whether or not a variable is empty in Bash?

Solution 1:

In Bash at least the following command tests if $var is empty:

if [[ -z "$var" ]]; then
   # Do what you want
fi

The command man test is your friend.

Solution 2:

Presuming Bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

Solution 3:

I have also seen

if [ "x$variable" = "x" ]; then ...

which is obviously very robust and shell independent.

Also, there is a difference between "empty" and "unset". See How to tell if a string is not defined in a Bash shell script.