How to Compare Strings in Bash


Bash Compare Strings
Bash Compare Strings

In order to compare Strings in Bash Scripts you can make use of the = operator or using == operator,

Example 1: Using = operator
% cat bash_example.sh  
#!/bin/bash
#Bash Compare Strings

StringA="HelloWorld"
StringB="HelloWorld"

if [ "$StringA" = "$StringB" ]; then
   echo "String A is equal to String B"
else 
   echo "String A is not equal to String B"
fi
Output:

String A is equal to String B

Example 1: Using == operator (pattern matching)
#!/bin/bash
#Bash Compare Strings

StringX="Java"
StringY="PHP"

if [[ "$StringX" == "$StringY" ]]; then
   echo "String X is equal to String Y"
else 
   echo "String X is not equal to String Y"
fi
Output:

String X is not equal to String Y

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.