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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap