How to Compare Strings in Bash Script

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 MethodsExplanation
[ "$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.

Compare Strings in Bash Script Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!