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

BashShellIs Empty

Bash Problem Overview


How can I check if a variable is empty in Bash?

Bash Solutions


Solution 1 - Bash

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 - Bash

Presuming Bash:

var=""

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

Solution 3 - Bash

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 https://stackoverflow.com/questions/228544/how-to-tell-if-a-string-is-not-defined-in-a-bash-shell-script.

Solution 4 - Bash

if [ ${foo:+1} ]
then
    echo "yes"
fi

prints yes if the variable is set. ${foo:+1} will return 1 when the variable is set, otherwise it will return empty string.

Solution 5 - Bash

if [[ "$variable" == "" ]] ...

Solution 6 - Bash

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

Solution 7 - Bash

The question asks how to check if a variable is an empty string and the best answers are already given for that.

But I landed here after a period passed programming in PHP, and I was actually searching for a check like the empty function in PHP working in a Bash shell.

After reading the answers I realized I was not thinking properly in Bash, but anyhow in that moment a function like empty in PHP would have been soooo handy in my Bash code.

As I think this can happen to others, I decided to convert the PHP empty function in Bash.

According to the PHP manual:

a variable is considered empty if it doesn't exist or if its value is one of the following:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • an empty array
  • a variable declared, but without a value

Of course the null and false cases cannot be converted in bash, so they are omitted.

function empty
{
    local var="$1"

    # Return true if:
    # 1.    var is a null string ("" as empty string)
    # 2.    a non set variable is passed
    # 3.    a declared variable or array but without a value is passed
    # 4.    an empty array is passed
    if test -z "$var"
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is zero (0 as an integer or "0" as a string)
    elif [ "$var" == 0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is 0.0 (0 as a float)
    elif [ "$var" == 0.0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return
    fi

    [[ $( echo "" ) ]]
}



Example of usage:

if empty "${var}"
    then
        echo "empty"
    else
        echo "not empty"
fi



Demo:
The following snippet:

#!/bin/bash

vars=(
    ""
    0
    0.0
    "0"
    1
    "string"
    " "
)

for (( i=0; i<${#vars[@]}; i++ ))
do
    var="${vars[$i]}"

    if empty "${var}"
        then
            what="empty"
        else
            what="not empty"
    fi
    echo "VAR \"$var\" is $what"
done

exit

outputs:

VAR "" is empty
VAR "0" is empty
VAR "0.0" is empty
VAR "0" is empty
VAR "1" is not empty
VAR "string" is not empty
VAR " " is not empty

Having said that in a Bash logic the checks on zero in this function can cause side problems imho, anyone using this function should evaluate this risk and maybe decide to cut those checks off leaving only the first one.

Solution 8 - Bash

This will return true if a variable is unset or set to the empty string ("").

if [ -z "$MyVar" ]
then
   echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
   echo "The variable MyVar has something in it."
fi

Solution 9 - Bash

You may want to distinguish between unset variables and variables that are set and empty:

is_empty() {
    local var_name="$1"
    local var_value="${!var_name}"
    if [[ -v "$var_name" ]]; then
       if [[ -n "$var_value" ]]; then
         echo "set and non-empty"
       else
         echo "set and empty"
       fi
    else
       echo "unset"
    fi
}

str="foo"
empty=""
is_empty str
is_empty empty
is_empty none

Result:

set and non-empty
set and empty
unset

BTW, I recommend using set -u which will cause an error when reading unset variables, this can save you from disasters such as

rm -rf $dir

You can read about this and other best practices for a "strict mode" here.

Solution 10 - Bash

To check if variable v is not set

if [ "$v" == "" ]; then
   echo "v not set"
fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTreeView Question on Stackoverflow
Solution 1 - BashJayView Answer on Stackoverflow
Solution 2 - BashChristopheDView Answer on Stackoverflow
Solution 3 - BashDaniel AnderssonView Answer on Stackoverflow
Solution 4 - BashalexliView Answer on Stackoverflow
Solution 5 - BashAmardeep AC9MFView Answer on Stackoverflow
Solution 6 - BashpixelbeatView Answer on Stackoverflow
Solution 7 - BashLuca BorrioneView Answer on Stackoverflow
Solution 8 - Bash3kstcView Answer on Stackoverflow
Solution 9 - BashdimidView Answer on Stackoverflow
Solution 10 - BashsmishraView Answer on Stackoverflow