How To Compare Strings In Bash
Before we dive in to string comparison in Bash. We should first look at the operators that are available for comparison in Bash.
s1 = s2 --> s1 matches s2
s1 != s2 --> s1 does not match s2
s1 < s2 --> s1 less than s2 (sort by alphabetical order and then compare)
s1 > s2 --> s1 greater than s2 (sort by alphabetical order and then compare)
-n s1 --> s1 is not null
-z s1 --> s1 is null
How To Compare Strings Using Equality Operator =
lets start with s1 = s2 operator.
lets declare two string variables.
s1="string1"
s2="string2"
if [ $s1 = $s2 ];then
echo "equal"
else
echo "not equal"
fi
not equal
if [[ $s1 = $s2 ]];then
echo "equal"
else
echo "not equal"
fi
not equal
Note, bash allows both [ and [[ for comparison. [[ is improvement over [ in bash.
For the rest of the post, I would use [[.
How To Compare Sentences in Bash.
s1="this is string1"
s2="this is string1"
if [[ $s1 = $s2 ]];then
echo "equal"
else
echo "not equal"
fi
equal
Note, we don't need double quotes when we are using double square brackets [[. Lets do above comparison using single square bracket [
if [ $s1 = $s2 ];then
echo "equal"
else
echo "not equal"
fi
bash: [: too many arguments
not equal
As we see, we got the error bash: [: too many arguments, to fix this we need to use double quotes around the variable.
if [ "$s1" = "$s2" ];then
echo "equal"
else
echo "not equal"
fi
equal
How To Use Not Inequality (!) Operator, For String Comparison In Bash
Lets use the inequality operator for the same s1 and s2 string comparison.
s1="this is string1"
s2="this is string1"
if [[ $s1 != $s2 ]];then
echo "notequal"
else
echo "equal"
fi
equal
How To Use Regexp ~ Operator For String Comparison In Bash
s1="string1"
s2="string2"
if [[ $s1 =~ [a-z]+ ]];then
echo "partially matched"
else
echo "equal"
fi
partially matched
How To Use Less than (<) and Greater Than(>) Operator For String Comparison In Bash
s1="john"
s2="chloe"
if [[ $s1 < $s2 ]];then
echo "s2 greater than s1"
else
echo "s2 less than s1"
fi
s2 less than s1
Lets change s2 to zuban
s1="john"
s2="zuban"
if [[ $s1 < $s2 ]];then
echo "s2 greater than s1"
else
echo "s2 less than s1"
fi
s2 greater than s1
How To Check If String Is Null Or Not Using -z or -n Switch In Bash
Last but not least lets check if string is null or not.
Lets create a null string.:
x=""
if [[ -z $x ]];then
echo "String is null"
fi
String is null
x="test"
if [[ -z $x ]];then
echo "String is null"
else
echo "string is not null"
fi
string is not null
Lets try -n switch for checking if variable is null or not.
if [[ -n $x ]];then
echo "String is null"
else
echo "string is not null"
fi
String is null
Wrap Up!
I hope you would find above post useful.
Related Topics:
Remove White Space In Text In Bash
Online White Space Remover Tool