How to Compare Strings in Bash With If Statement [6 Methods]

String comparison is the process of checking if a string is the same length as another string, if it’s longer or shorter, or if it’s empty. To compare strings in bash, there are some comparison operators such as =, <, ==, >, !=, -z, -n. In addition, Case statements can be used to perform string comparisons.

In this article, I will show 6 different ways to do string comparisons in bash. Also, I’ll discuss some common mistakes of string comparison to help you avoid them.

Operators to Compare Strings in Bash

Comparison operators that are used with bash’s if-else expression to compare strings:

Operator Syntax Description
Equal to (=) if [ “$string1” = “$string2” ] Returns true if the string1 is equal to string2.
Double Equal to (==) if [[ “$string1” == “$string2” ]] Returns true if the string1 is equal to string2.
Not Equal to (!=) if [ “$string1” != “$string2” ] Returns true if the string1 is not equal to string2.
regex (=~) if [[ “$string1” =~ “$string2” ]] Returns true if the string1 matches the extended regular expression of string2.
Greater than (>) if [[ “$string1” > “$string2” ]] or

if [ “$string1” > “$string2” ]

Returns true if the string1 is greater than string2 sorted alphabetically.
Less than (<) if [[ “$string1” < “$string2” ]] or

if [ “$string1” > “$string2” ]

Returns true if the string1 is less than string2 sorted alphabetically.
-z if [[ -z “$string” ]] or if [ -z “$string” ] Returns true if the string is empty.
-n if [[ -n “$string” ]] or if [ -n “$string” ] Returns true if the string is not empty.

Note: Make sure to double-check the syntax to prevent the bash script from making syntax errors.

1. Compare If Strings are Equal in Bash

To compare if strings are equal in bash, use the = and == operators. The details are discussed below:

Using Single Equal To “=”

To compare strings in bash with the = operator, use this syntax [ "$string1" = "$string2" ] inside the if condition. This expression returns true if the length of the strings are the same otherwise, returns the false output. Here’s how it works:

#!/bin/bash
string1="Linuxsimply.com"
string2="linuxsimply.com"
if [ "$string1" = "$string2" ]; then
echo "strings are equal."
else
echo "strings are different."
fi
EXPLANATION

If both strings are the same, the script will execute the if block and print”strings are equal.”. On the other hand, it will execute else section and print “strings are different”.

checking equality between strings to compare in bash

In this image, you can see that the strings are different, as string1 contains the capital letter L “Linuxsimply.com” but string2 starts with a small letter l “linuxsimply.com”.

Note: You can use if [[ "${string1,,}" = "${string2,,}" ]] instead of if [ "$string1" = "$string2" ] to ignore case sensitivity.

Using Double Equal To “==”

To check equality between strings, use the == operator within double square brackets “[[” to ignore syntax error. See the script for further information:

#!/bin/bash
string1="Linuxsimply.com"
string2="Linuxsimply.com"
if [[ "$string1" == "$string2" ]]; then
echo "strings are equal"
else
echo "strings are different"
fi
EXPLANATION

The script will execute the if block and print the statement strings are equal if both strings are identical. Conversely, it will execute else block and print strings are different.

checking equality between strings using double equal to operator to compare in bash

The output shows that strings are equal as both strings have Linuxsimply.com in them.

2. Compare Strings Lexicographically (Alphanumeric) in Bash

Comparing strings lexicographically is a process of translating each character of a string to Unicode and comparing its value from the initial character on the left to the final character on the right until a null value is found.

To compare if a string is greater than another, use this code [[ "$string1" > "$string2" ]] with the if-else statement. Here’s how:

#!/bin/bash
string1="Apple"
string2="Linuxsimply"
if [[ "$string1" > "$string2" ]]; then
echo "$string1 is greater than $string2"
else
echo "$string1 is not greater than $string2"
fi
EXPLANATION

The script returns “Apple is greater than Linuxsimply (alphabetically)” when the condition is true. Otherwise, it will print the else block expression.

checking if the string1 is greater than string2

As you can see in this image Apple is not greater than Linuxsimply because the Unicode of L(U+004C) is greater than the Unicode of A(U+0041). So, Linuxsimply is bigger than Apple.

To verify if the string1 is smaller than string2, use the less than operator <strong><</strong> instead of <strong>></strong> within the if statement. Here’s the bash script for this:

#!/bin/bash
string1="Apple"
string2="Linuxsimply"
if [[ "$string1" < "$string2" ]]; then
echo "$string1 is less than $string2"
else
echo "$string1 is not less than $string2"
fi
EXPLANATION

When string1 is less than string2 in alphabetical order, the script returns “Apple is less than Linuxsimply”. Contrarily, it will execute the else block statement.

checking if the string1 is less than string2

From the above picture, you can observe that Apple is less than Linuxsimply as the Unicode value of “A” is smaller than the value of “L”.

3. Compare Strings with Empty String in Bash

An empty string is a string with zero length. In Bash, you can compare the strings by checking whether they are empty or not using the -z or -n operators. There are other methods as well to check if the string is empty. Now, Let’s look at how the -z and -n options work:

Using -z

The -z parameter measures the length of the string. If the specified string length is either zero or empty, a true expression is executed.

#!/bin/bash
string="Linuxsimply"
if [[ -z "$string" ]]; then
echo "Empty string"
else
echo "The string is not empty"
fi
EXPLANATION

If the string is empty, it will execute the if block statement. On the other hand, it will print the else block expression “The string is not empty”.

checking if the string is empty in bash

Since the string length is not zero and contains “Linuxsimply“, the script will echo the false code block “The string is not empty”.

Using -n

Unlike -z, the -n option checks if the string length is not zero and returns a true statement. Here’s how:

#!/bin/bash
string="Linuxsimply"
if [[ -n "$string" ]]; then
echo "The string is not empty"
else
echo "Empty string"
fi
EXPLANATION

When the string length is not zero, it will display the if block code “The string is not empty” otherwise, it will show the else code block.

checking if the string is not empty in bash

The image shows that the string is not empty, because it has the word Linuxsimply in it.

4. Compare Strings for Searching a Substring in Bash

To check if a string contains a substring, use an asterisk (*) sign or regex operator (=~). Let’s check the approaches in detail.

Using Asterisk (*)

The asterisk symbol (*) surrounding the substring indicates that the substring matches all the characters. Check the script below to see how to find the substring:

#!/bin/bash
string="Linux is an operating system"
if [[ $string == *"operating"* ]]; then
echo "string contains the substring"
else
echo "string does not contain the substring"
fi
EXPLANATION

This script checks if $string has the substring “operating” in it. If it does, bash will print “string contains the substring”. Otherwise, bash will write “string does not contain the substring”.

searching for a substring using asterisk

You can see in the image that it displays string contains the substring because the * wildcard prior and after “operating” permits the presence of any characters (including no characters) before and after the string word “operating”.

Using Regex

To match strings based on a specific pattern, use this syntax if [[ $string =~ .*operating.* ]]. The regular expression “.*operating.*” matches any string containing the word “operating”, with zero or more characters preceding and after the word. Review the script for further information:

#!/bin/bash
string="Linux is an operating system"
if [[ $string =~ .*operating.* ]]; then
echo "string contains the substring"
else
echo "string does not contain the substring"
fi
EXPLANATION

In the predefined string “Linux is an operating system”, if the expression “operating” is present, the condition evaluates to true. Otherwise, the condition evaluates to false.

searching for a substring using regex

You can see in this picture that “string contains the substring” as the expression “operating” is present in the main string.

5. Compare If Strings are Unequal in Bash

To check if the strings are unequal, use not equal to operator != within the if condition. The condition returns true if the strings are not equal to each other. Check the script to get clearer insight:

#!/bin/bash
string1="Ubuntu"
string2="Linux"
if [ $string1 != $string2 ]; then
echo "strings are different"
else
echo "strings are equal"
fi
EXPLANATION

When string1 is not equal to string2, it will show “strings are different” otherwise, it will execute the else block statement.

checking if strings are not equal

As you can see Ubuntu and Linux are not the same, so it prints “strings are different”.

To compare the user-defined string value with a specified string value with the not equal to operator !=, check the following bash script:

#!/bin/bash
echo "Enter a string value"
read string
if [ $string != "Linuxsimply" ];
then
echo "No match Found"
else
echo "Match Found"
fi
EXPLANATION

If you enter any value that is not equal to “Linuxsimply”, then the if block is executed. But if you enter a string that matches the specified string, then the code block “Match Found” is executed.

comparing user defined string

As you can see when I typed hello as an input string, it didn’t match anything. But when I typed Linuxsimply, it did. It found the match and showed “Match found”.

6. Compare Strings with Case Operator

The case statement is a conditional structure used to perform conditional branching based on different patterns like letters, numbers, special characters, and so on. In this example, I will use this conditional statement to compare multiple strings.

Check the script to know how to compare multiple strings using a case statement:

#!/bin/bash
shopt -s nocasematch
echo "Enter a Linux distro name: "
read string
case $string in
"Ubuntu" | "Arch Linux")
echo "It’s a Debian-based Linux Distro"
;;
"Fedora" | "CentOS")
echo "It’s a Red Hat-based Linux Distro"
;;
*)
echo "unknown distro."
;;
esac
EXPLANATION

Here, shopt -s nocasematch command enables case-insensitive matching in the script. If the input string is “Ubuntu” or “Arch Linux”, it will print “It’s a Debian-based Linux Distro”. If the input string is “Fedora” or “CentOS”, it will execute “It’s a Red Hat-based Linux Distro”. When the input string doesn’t match any of the specified cases, it will print “unknown distro.”

comparing strings in bash using case statements

This picture shows that when I enter ubuntu, it shows “It’s a Debian-based Linux Distro”. If I enter fedora, it displays “It’s a Red Hat-based Linux Distro”. However, if I enter kali linux which is not specified in the cases, it executes “unknown distro”.

Common Mistakes of String Comparison in Bash

In bash, some common errors can occur while comparing strings and can reduce the performance of your scripts. Here I will explain some common mistakes and their solutions:

Ignoring Double Quotes

You can write strings within a single quote, however, this can result in unexpected behavior, particularly when the string includes spaces or unique characters.

Therefore, it is important to enclose string variables within double quotes when comparing strings in Bash to guarantee that strings are interpreted correctly.

Wildcards Mistakes

Wildcards are a bit confusing so use them with caution in pattern matching to get the desired output. For example:

#!/bin/bash
string="Linux is an operating system"
if [[ $string == *operating* ]]; then
echo "string contains the substring"
fi

You can see in this script that wildcards are misplaced, they should be placed with the pattern enclosed with double quotes. Check the correct script below:

#!/bin/bash
string="Linux is an operating system"
if [[ $string == *"operating"* ]]; then
echo "string contains the substring"
fi

Mistake Using “==” in Single Square Brackets [ ]

The “double equal to” operator == is more advanced than the “single equal to” = operator. So using this syntax [ "$string1" == "$string2" ] to check the equality between string1 and string2 can lead to errors.

To avoid these mistakes in string comparison, use [[ "$string1" == "$string2" ]] within the if condition instead of [ "$string1" == "$string2" ].

Overlooking Exit Codes

Entering a command in bash returns an exit code. A value of 0 indicates that the command was executed successfully, while 1 indicates an error. Here’s an example:

#!/bin/bash
string1="Linuxsimply.com"
string2="Linuxsimply.com"

# Perform the string comparison and store the exit status in a variable
comparison_status=$?
if [[ "$string1" == "$string2" ]]; then
echo "Strings are equal."
if [ $comparison_status -eq 0 ]; then
echo "String comparison successful."
else
echo "String comparison failed."
fi
fi

After running the script, you will get the following output:

checking exit code of a string comparison

This indicates that the condition is evaluated to be true and that the comparison is completed successfully.

Note: Before performing any comparison, it is recommended to check the exit status to prevent some silent errors.

Conclusion

I hope this article helps you to understand how to compare strings in bash. Here, I have demonstrated 6 methods to check if the strings are equal or empty or larger or smaller. Moreover, performing substring searching has been explained here.

People Also Ask

How can I compare strings in Bash?

To compare strings in Bash, you can use the comparison operator (==, >, <) within an if statement. Here’s an example:

#!/bin/bash

string1="Hello"
string2="World"

if [ "$string1" == "$string2" ]; then
echo "Strings are equal."
elif [ "$string1" > "$string2" ]; then
echo "String 1 is greater than String 2."
else
echo "String 2 is greater than String 1."
fi

What is the difference between “==” and “=~” operators in Bash string comparison?

The == operator does a simple, exact comparison of two strings whereas the =~ operator does regular expression matching, which means you can compare a string to a regular expression.

What is the difference between “=” and “==” bash operators in string comparison?

In bash, you can use both = and == to compare strings. The main difference is that within a double square bracket “[[“, == and = operators are interchangeable but within a single bracket “[“, only = can be used.

How can I determine string length in Bash?

To determine string length (number of characters in a string), you can use length=${#string} syntax. Here’s an example script below:

#!/bin/bash
string="Linuxsimply.com"
length=${#string}
echo $lenght

How to convert string cases from uppercase to lowercase?

To convert a whole string from uppercase to lowercase, use lowercase="${original_string,,}" which converts the value of original_string to lowercase using the ,, operator and assigns the result to the variable lowercase. Here’s how it works:

#!/bin/bash
original_string="LINUXSIMPLY"
lowercase="${original_string,,}"
echo $lowercase

How to convert string cases from lowercase to uppercase?

To convert a whole string from lowercase to uppercase, use uppercase="${original_string^^}" that converts the value of original_string to uppercase using the ^^ operator and assigns the result to the variable uppercase. Check the following script:

#!/bin/bash
original_string="linuxsimply"
uppercase="${original_string^^}"
echo $uppercase

How can I compare strings based on string length?

To compare strings based on their length, you can use [ "${#string1}" -lt "${#string2}" ] syntax inside the if condition. Here’s how:

#!/bin/bash
string1="ubuntu"
string2="linuxsimply"
if [ "${#string1}" -lt "${#string2}" ]
then
echo "string1 is shorter than string2"
fi

Here, ${#string} is used to determine the length of each string, and then the -lt operator is used to determine whether the first string is smaller than the second string. In this case, the script will display “string1 is shorter than string2” in the output.

Related Articles


<< Go Back to If Else in Bash | Bash Conditional Statements | Bash Scripting Tutorial

5/5 - (10 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment