Bourne/bash shell scripts: string comparison

Contributor Icon Contributed by Rex Date Icon October 21, 2003  
Tag Icon Tagged: Bourne shell scripting


To determine if the value of a variable ($var) is empty (null):

if [ $var == "" ]
then
echo variable is null
fi

To determine if the value of a variable is not empty:

if [ $var != "" ]
then
echo variable is not null
fi

To compare the contents of a variable to a fixed string:

if [ $var == "value" ]
then
echo is the same
fi

To determine if variable’s contents are not equal to a fixed string:

if [ $var != "value" ]
then
echo not the same
fi

Previous recipe | Next recipe |
 
  • Florin
    This is the method i curently to test if a string is empty:

    if [ "X${VAR}" = "X" ]; then
    echo "Empty string"
    fi

    Testing for equality follows the same logic but without X.
  • asd
    These examples don't work.
  • bhargav
    if [ "$var" = "value" ]
    then
    echo not the same
    fi
  • BhupinderSingh
    this can also be used to compare 2 strings

    s1 = "as"
    s2 = "bs"

    if test $s1 == $s2
    then
    echo s1 and s2 are equal
    fi
  • BhupinderSingh is a layer
    You're lying. That dosen't work.
    test: 40: ==: unexpected operator
  • guest
    the following syntax is wrong

    if [ $var == "" ] ......

    because if the variable $var is empty the test is
    if [ == "" ] and gives an error

    you are obliged to quote the var :
    if [ "$var" == "" ] ...


    Sergio
  • Anonymous
    Wouldn't the following be better?

    if [ -z $var ];then
    echo null
    fi
  • Anonymous
    i believe the $var needs to be in quotes, like so:

    if [ -z "$var" ];then
    echo null
    fi

    Best Regards,
    Kibokina
  • netuddki
    The correct solution is here a year ago. It should be corrected in the article too, so one won't try those for 10 minutes before finding the answer here.
blog comments powered by Disqus