Bash Compare Strings

Bash Compare Strings

Similar to other programming languages, strings in bash is the datatype that holds a sequence of characters.

In this tutorial, you will learn how to compare the bash strings using the various comparison operators discussed below.

Firstly, let’s see an example of creating and running a bash script.

Create a file testscript.sh and write the following codes in the file.

testscript.sh
#!/bin/bash

greetings="namaste"
echo $greetings
Output
namaste
Note: The first line in the script is called shebang, which is the absolute path to the bash interpreter.

Bash String Comparison Operators

This section describes the various comparison operators used to compare bash strings. The result of the comparison is either true or false.

  • string1=string2: The single equals operator, <strong>=, checks if string1 and string2 are equal. For example, if both the strings contain the same text, hello!, the comparison returns true. The operands are wrapped inside [] while using =.
  • string1==string2: The double equals operator, == also checks if the two strings are equal. Here, the operands are wrapped inside [[]].
  • string1!=string2: The inequality operator, != checks if string1 is not equal to string2. It returns true if they are not equal.
  • string1>string2: The greater than operator > checks whether the string on the left side is greater than the one on the right side. The comparison between the strings is made based on their alphabets.
  • string1<string2: The less than operator < checks whether the string on the left side is less than the one on the right side. It returns true on success.
  • string=~regex: The expression checks if string matches the extended regex and returns true on success.
  • -z string: The expression checks whether the length of string is 0 and returns true on success.
  • -n string: The expression checks whether the length of string is not 0 and returns true on success.

Check Whether Two Strings are Equal

You can check whether two strings are equal using either of the three operators in bash. The operators are single equals, double equals, and inequality operators. The example code is shown below.

#!/bin/bash

String1="Good Morning!"
String2="Good Morning!"
String3="good morning!"

if [ "$String1" = "$String2" ]; then
    echo "String1: ${String1} and String2: ${String2} are equal."
else
    echo "String1: ${String1} and String2: ${String2} are not equal."
fi

if [[ "$String1" == "$String2" ]]; then
    echo "String1: ${String1} and String2: ${String2} are equal."
else
    echo "String1: ${String1} and String2: ${String2} are not equal."
fi

if [[ "$String1" != "$String3" ]]; then
    echo "String1: ${String1} and String3: ${String3} are not equal."
else
    echo "String1: ${String1} and String3: ${String3} are equal."
fi

 

Output
String1: Good Morning! and String2: Good Morning! are equal.
String1: Good Morning! and String2: Good Morning! are equal.
String1: Good Morning! and String3: good morning! are not equal.

In the above example, you can see the use of the if-else statement to perform conditional checking to print the result. The fi statement indicates the end of each if-else block. The two operand strings should be exactly the same(also case-sensitive) to evaluate true. Thus, you can check the exactness of the string.

Compare Lexicography of Two Strings

You can perform the lexicographic comparison of the two strings in bash using the greater than, > or the less than, < operators. In lexicographic order, the uppercase is bigger than the lower case. When the case is the same, the comparison is based on the alphabetical order of the two strings. The comparison between the strings is made from the left to the right. Look at the practical implementation below to understand the concept.

#!/bin/bash

car1="Lamborghini"
car2="Audi"

if [[ "$car1" > "$car2" ]]; then
    echo "${car1} is greater than ${car2}."
elif [[ "$car1" < "$car2" ]]; then
    echo "${car2} is greater than ${car1}."
else
    echo "Both the cars are equal"
fi
Output
Lamborghini is greater than Audi.

In the above example, the strings car1 and car2 that hold the value Lamborghini and Audi are compared. In lexicographic order, L is treated as greater than A, which are the first letters of each string.

This is because the Unicode character of L (U+004C) is greater than that of the A (U+0041). Therefore, the string Lamborghini is evaluated as greater than Audi.

Check Whether a String is Empty

You can check whether a string is empty using the -n or -z operator. The example is shown below.

#!/bin/bash

name=""
address="pokhara"
if [[ -z $name ]]; then
    echo "the string: name is empty."
fi

if [[ -z $address ]]; then
    echo "the string: address is not empty."
else
    echo "the address is ${address}"
fi
Output
the string: name is empty
the address is pokhara

In the demonstration above, one of the strings among the two is empty. The -z $name expression returns true as $name is empty. Thus, the if block gets executed. Meanwhile, the expression -z $address returns false as $address is not empty. As a result, the else block gets executed.

You can also use the -n operator for a similar scenario.

#!/bin/bash

name="Alan"
job=""
if [[ -n $name ]]; then
    echo "the string: name is not empty, the value is ${name}"
fi

if [[ -n $job ]]; then
    echo "the string: job is not empty."
else
    echo "the string: job is empty"
fi
Output
the string: name is not empty, the value is Alan
the string: job is empty

The above example shows that -n string returns true when string is not empty. So the if block gets executed while checking for the name string. When the empty string job is checked, it returns false, and the else block gets executed.

Check Whether a String Contains a Substring

You can use the regex operator, =~, to check whether a string contains a substring. The left side of the operator contains the string, while the right side contains the substring to be checked. A simple example is shown below.

#!/bin/bash

day='Today is Monday!'
if [[ $day =~ Monday ]]; then
    echo "Substring found."
else
    echo "Substring not found."

fi

if [[ $day =~ Sunday ]]; then
    echo "Substring found."
else
    echo "Substring not found."
fi
Output
Substring found.
Substring not found.

In the example above, the string is Today is Monday!. Two substrings, Sunday and Monday, are checked against the string. Since the string contains Monday, the if block gets executed as it evaluates true. For Sunday, it does not exist in the string. As a result, the comparison results in the false and else block getting executed.

Conclusion

In this tutorial, you got the idea of some of the common bash string comparison operators. Finally, you learned how to use those operators to compare the bash strings provided in different scenarios.

 

0 Shares:
Subscribe
Notify of
guest
Receive notifications when your comment receives a reply. (Optional)
Your username will link to your website. (Optional)

0 Comments
Inline Feedbacks
View all comments
You May Also Like
Bash Append to File
Read More

Bash Append to File

There are various ways to append text to a file in bash. In computing, append means to add…
gnome logo with theme icon
Read More

How to Install GNOME Themes

Knowing how to install GNOME themes empowers you to customize the appearance of your Linux graphical user interface.…