Bourne/bash shell scripts: string comparison

Posted November 18, 2010 by Rex in Bourne shell scripting

Brief tutorial describing how to do string comparisons. Recently updated thanks to comments from our users.

Our original tutorial needed correcting for the case if $var is null. We have updated our original article.

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

The Conversation

Follow the reactions below and share your own thoughts.