In Bash you quite often need to check to see if a variable has been set or has a value other than an empty string. This can be done using the -n or -z string comparison operators.

The -n operator checks whether the string is not null. Effectively, this will return true for every case except where the string contains no characters. ie:

if [ -n "$VAR" ]; then
    echo "VAR is not empty"

Similarly, the -z operator checks whether the string is null. ie:

if [ -z "$VAR" ]; then
    echo "VAR is empty"

Note the spaces around the square brackets. Bash will complain if the spaces are not there.

  1. Sanches says:

    What about, if the string looks empty but is not?

    If I do like:

    A=`some command’ # <== Returning some whitespace chars

    and now

    if [ -z "$z" ]; then echo Yippy; fi

    it gives me always nothing in my case.

  2. Sanches says:

    Ok, forgot the dollar symb.

  3. Dennis says:

    Since -n is the default operation, you can also do

    if [ “$VAR” ]; then

    to check for a non-empty string.

  4. […] via Checking for empty string in Bash « […]

  5. Axel says:

    Thanks 🙂

  6. Tiffany says:

    Short and to the point, thanks !!!

  7. DaveVanHandel says:

    Also, with -n, you must surround the variable with the double quotes.
    For example, if you do:

    unset var1
    if [ -n $var1 ]; then
    echo set
    echo not set

    it will echo ‘set’. If you put the double quotes around $var1, it will echo ‘not set’

  8. Bram says:

    In reply to DaveVanHandel;

    Any bash test without an argument will return true. Quoting the variable is required so that the test will have at least an (empty) argument, even when the variable is not set.

    For example, If $a is empty (a=””), then:

    if [ -n $a ]

    would be the same as:

    if [ -n ] (true)

    There you have the -n test without arguments.

    When quoted the empty variable would be treated as an argument, so:

    if [ -n “$a” ],

    would be the same as:

    if [ -n “” ]

    I ran into this issue with the file test operator (-f).