Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1
String Comparison

You can use the following operators to compare two string expressions:


=—Compares  whether two strings are equal
!=—Compares whether two strings are not equal
-n—Evaluates whether the string length is greater than zero
-z—Evaluates 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:


Click here to view code image
#!/bin/sh
string1="abc"
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"
fi

If you execute compare1, you get the following result:


Click here to view code image

Free download pdf