as We generally use bash
in order to execute commands. But as bash is a programming environment we have other programming related features. We can compare strings where these strings are output or error of some commands. In this tutorial we will look different use cases for string comparison in Bash Linux.
Compare with Equality
The most used examples for string comparison is comparing equality. We can compare two strings character by character for equality and then return some value or string according to the result. In this example we will check two string variables $s1
$s2
and return result as string like EQUAL
or NOTEQUAL
. We will use ==
for string equality check. -eq
will not work because it is only used with numbers or integers.
s1='poftut' s2='poftut' if [ "$s1" == "$s2" ] ; then echo "EQUAL"; fi

Compare For Not Equal
We can use not
logic for inequality this is useful like password check. We will check stored password and provided password.We can will use !=
as inequality operator.
password="secret" read provided_password if [ "$password" != "$provided_password" ] ; then echo "Wrong Password"; fi

As we can see provided password is different from secret
and we print Wrong Password
to the screen.
Compare Case-Insenstive
While comparing strings case sensitivity is important factor. The default behavior is comparing strings in case sensitive but in some cases we may need to compare them case-insensitive. We can use bash provided nocasematch
feature. This feature will disable case sensitivity for bash completely.
shopt -s nocasematch s1='poftut' s2='PoftuT' [[ "$s1" == "$s2" ]] && echo "EQUAL" || echo "NOT EQUAL"
