Bash – Check If Two Strings are Equal
Brief: This example will help you to understand to check if two strings are equal in a bash script. This shell script accepts two string in variables and checks if they are identical.
Details
- Use
==
operator with bash if statement to check if two strings are equal. - You can also use
!=
to check if two string are not equal. - You must use single space before and after the
==
and!=
operators.
Example
In this script two variables are initialized with predefined strings. Now check if both strings are equal or not with ==
operator.
1 2 3 4 5 6 7 8 9 10 | #!/bin/bash str1="Hello Bash" str2="Hello Bash" if [ "$str1" == "$str2" ]; then echo "Strings are equal" else echo "Strings are not equal" fi |
Output:
Strings are equal
Another Example
Use below sample shell script to take input from the user and check if given strings are equal or not.
1 2 3 4 5 6 7 8 9 10 | #!/bin/bash read -p "Enter first string: " str1 read -p "Enter second string: " str2 if [ "$str1" == "$str2" ]; then echo "Strings are equal" else echo "Strings are not equal" fi |
Script execution results:
First Run: StEnter first string: welcome bash Enter second string: welcome bash Strings are equal Second Run: Enter first string: Welcome bash Enter second string: hello bash Strings are not equal