String Comparisons

String Comparisons

str1 = str2 Checks if str1 is the same as str2
if [ $str1 = $str2 ]
then
do_something()
fi
str1 != str2 Checks if str1 is not the same as str2
if [ $str1 != $str2 ]
then
do_something()
fi
str1 < str2 Checks if str1 is less than str2
if [ $str1 \< $str2 ]
then
do_something
fi
str1 > str2 Checks if str1 is greater than str2
if [ $str1 \> $str2 ]
then
do_something
fi
-n str1 Checks if str1 has a length greater than zero
if [ -n $str1 ]
then
do_something
fi
-z str1 Checks if str1 has a length of zero
if [ -z $str1 ]
then
do_something
fi

Looking at String Order

Trying to determine if one string is less than or greater than another is where things start getting tricky. Two problems often plague shell programmers when trying to use the greater-than or less-than features of test conditions:

  • The greater-than and less-than symbols must be escaped, or the shell uses them as redirection symbols, with the string values as filenames.

  • The greater-than and less-than order is not the same as that used with the sort command