Bourne/bash shell scripts: string comparison
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" == "" ]
echo variable is null
To determine if the value of a variable is not empty:
if [ "$var" != "" ]
echo variable is not null
To compare the contents of a variable to a fixed string:
if [ "$var" == "value" ]
echo is the same
To determine if variable’s contents are not equal to a fixed string:
if [ "$var" != "value" ]
echo not the same
Follow the reactions below and share your own thoughts.