String Comparison

The following operators can be used to compare two string expressions:

= To compare whether two strings are equal

! = To compare whether two strings are not equal

-n To evaluate whether the string length is greater than zero

-z To evaluate whether the string length is equal to zero

Next are some examples using these operators when comparing two strings, string1 and string2, in a shell program called compare1:

string2="abd"

if [ $string1 = $string2 ]; then echo "string1 equal to string2" else echo "string1 not equal to string2"

fi if [ $string2 != string1 ]; then echo "string2 not equal to string1" else echo "string2 equal to string2"

fi if [ $string1 ]; then echo "string1 is not empty" else echo "string1 is empty"

fi if [ -n $string2 ]; then echo "string2 has a length greater than zero" else echo "string2 has length equal to zero"

fi if [ -z $string1 ]; then echo "string1 has a length equal to zero" else echo "string1 has a length greater than zero"

If you execute compare1, you get the following result:

string1 not equal to string2

string2 not equal to string1 string1 is not empty string2 has a length greater than zero string1 has a length greater than zero

If two strings are not equal in size, the system pads out the shorter string with trailing spaces for comparison. That is, if the value of string1 is abc and that of string2 is ab, string2 will be padded with a trailing space for comparison purposesit will have a value of ab.

Was this article helpful?

0 0

Post a comment