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


Top Hashtags:

Advertisements

Advertisements




Advertisements