Compare Strings

To compare strings in Bash, we can check if the two strings are equal, if one string is greater than the other, or if one string is less than the other, etc., using string comparison operators.

String Comparison Operators

The following table shows some of the string comparison operators that we would like to discuss in this tutorial.

OperatorNameExampleDescription
=Equal to[ string1 = string2 ]Returns true if both the strings are equal.
\>Greater than[ string1 \> string2 ]Returns true if left operand string is greater than the right operand string.
\<Less than[ string1 \< string2 ]Returns true if left operand string is less than the right operand string.
ADVERTISEMENT

Examples

Compare if Strings are Equal

In the following script, we take two strings in s1 and s2, and compare them to check if they are equal.

Example.sh

s1="apple"
s2="apple"

if [ $s1 = $s2 ];
then
    echo "Strings are equal."
else
    echo "String are not equal."
fi

Output

Strings are equal.

Compare if a String is Greater than Other String

In the following script, we take two strings in s1 and s2, and compare them to check if s1 is greater than s2.

Example.sh

s1="banana"
s2="apple"

if [ $s1 \> $s2 ];
then
    echo "$s1 is greater than $s2."
else
    echo "$s1 is not greater than $s2."
fi

Output

banana is greater than apple.

Compare if a String is Less than Other String

In the following script, we take two strings in s1 and s2, and compare them to check if s1 is less than s2.

Example.sh

s1="banana"
s2="mango"

if [ $s1 \< $s2 ];
then
    echo "$s1 is less than $s2."
else
    echo "$s1 is not less than $s2."
fi

Output

banana is less than mango.

Equal to, Greater than or Less than

Let us use elif statement to put all the above three comparisons together.

Example.sh

s1="banana"
s2="mango"

if [ $s1 = $s2 ];
then
    echo "Both the strings are equal."
elif [ $s1 \> $s2 ];
then
    echo "$s1 is greater than $s2."
elif [ $s1 \< $s2 ];
then
    echo "$s1 is less than $s2."
fi

Output

banana is less than mango.

Conclusion

In this Bash Tutorial, we have learnt how to compare strings in Bash script using string operators.