Let's see a few examples of how to compare Strings in a Bash Script,
Example 1: using [ ]
#!/bin/bash
name1="Mike"
name2="Mikey"
if [ "$name1" = "$name2" ]; then
echo "Both names are the same."
else
echo "Both names are not the same."
fi
Example 2: using (( ))
#!/bin/bash
name1="Mike"
name2="Mikey"
if (( "$name1" == "$name2" )); then
echo "Both names are the same."
else
echo "Both names are not the same."
fi
Example 2: using [[ ]]
#!/bin/bash
name1="Mike"
name2="Mikey"
if [[ "$name1" == "$name2" ]]; then
echo "Both names are the same."
else
echo "Both names are not the same."
fi
| Comare String Methods | Explanation |
|---|---|
[ "$string1" = "$string2" ] |
To check if two strings are equal. |
[ "$string1" != "$string2" ] |
To check if two strings are not equal. |
(( "$string1" == "$string2" )) |
To perform a numeric comparison for equality (0) or inequality (1). |
[[ "$string1" == "$string2" ]] |
To perform pattern matching and string comparison. |

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!