Bash Strings Comparison: 4 Ways To Check if Two Strings Are Equal

While writing Bash scripts we will often required  to compare two strings to evaluate if they are equal or not. The two strings are equal when they have same length and contain same sequence of characters.

In this article, we’ll look at some of the techniques to compare bash strings and explore several methods that can use to evaluate if two strings are equal. We’ll explain each technique with proper that will provide you a better understanding and a solid foundation for the future Bash scripting tasks. Now let’s dig in to the article.

What is Bash String? 

Bash String is the type of data that is similar to boolean or integer. It is usually used to represent the text. It is the string of characters which might also contain numbers enclosed within single or double quotes.

Comparing The Bash  Strings:  All the Techniquesbash strings all the technquies

1. Equality and Inequality Operators

The most common way to compare two bash strings is to check whether they are the same or not. This can be done by using double equal signs (==) for equality and for the  “not equal” operator use the combination (!=).

Here are examples of each:

if [ "perimattic1" == "perimattic2" ]; then echo "Equal"; fi
if [ "perimattic1" != "perimattic2" ]; then echo "Not equal"; fi

In the above code we have compared variables as perimattic1  and perimattic2.

The equality and inequality operators are much easier to understand, and the ones you will be using a lot in bash string when checking roles or permissions.

2. Numerical Comparison

If you have two numbers in bash, stored in variables, and want to check which one is greater than then you have to use something known as “numerical comparison”, that is very different from what you have been using to in other languages that treat variables differently depending on how they are declared.

For numerical comparisons, bash has the following operators:

  1. eq – equality
  2. lt – inequality
  3. le – lesser than or equal
  4. gt – greater than
  5. ge – greater than or equal
  6. ne – not equal

Here’s a example of using the “lesser than” operator:

c="10"
d="20"
if [ "$c" -lt "$d" ]; then
    echo "$c is less than $d”
fi

In this example, the two variables $a and $b are numbers. However, they’re represented by strings internally, so when we want to check if one is lesser than the other, we use the “lt” numerical operator.

To use the numerical operators, you must use them with a dash (-) as shown in the examples above. They are not as intuitive to write as regular comparison operators in other languages. However, because bash treats all variables as strings, we have no choice left but to use these slightly unintuitive operators for numerical comparisons.

3. Partial String Matching

Partial string matching in Bash can be achieved using various methods such as pattern matching with wildcards, substring extraction, or regular expressions. Here are some examples:

partial string matching

1. Pattern Matching with Wildcards:

string="HelloWorld"

# Check if the string contains "Hello" anywhere in it
if [[ "$string" == *"Hello"* ]]; then
echo "Partial match found: Hello"
else
echo "No partial match for: Hello"
fi

2. Substring Extraction:

string=”HelloWorld”

# Extract a substring and check if it matches
substring=”World”
if [[ “$string” == *”$substring”* ]]; then
echo “Partial match found: $substring”
else
echo “No partial match for: $substring”
fi

 

3. Regular Expressions:

string="HelloWorld"

# Use regular expressions to check for a partial match
if [[ "$string" =~ "Hello" ]]; then
echo "Partial match found: Hello"
else
echo "No partial match for: Hello"
fi

4. Regex String Comparisons

Bash string permits you to compare it to regular expressions. For example:

if [[ "$str" =~ ^[a-zA-Z]+$ ]]; then echo "str is alphabetic"; fi

In the above example, “$str” with a regular expression that checks to see if the string is alphabetic. Since regexes use square brackets for their expressions, the matching needs you to use double square brackets [[ ]] for partial string matching.

5. String Length Comparisons

Instead of comparing the contents of two strings, you can also compare their length by using the hash (#) operator and can compare lengths by utilizing the numerical comparison.

Bash Strings Compare: How to Check if Two Strings Are Equal with Example

Create a Script File

The first step to check if two strings are equal by creating a script file.

#!/bin/bash

string1="perimattic"
string2="company"

if [[ "$string1" == "$string2" ]]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi

Now that we have our script file ready, let’s now move on to the next step where we will try the several techniques to check if the two strings are equal.

Technique1: Check if Two Strings Are Equal with the test Command

The test command is the built-in shell command that is utilized to evaluate conditional expressions. It has the following syntax:

test expression

Let’s now write a script using the testcommand to check if two strings are equal. Here’s the script:

#!/bin/bash

string1="perimattic"
string2="perimattic"

if test "$string1" = "$string2"; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi

In this script:

– We assign the strings “perimattic” and “perimattic” to the variables `string1` and `string2`, respectively.
– Then, we use the `test` command with the equal (`=`) operator to compare the two strings.
– If the strings are equal, the script prints “Strings are equal”; otherwise, it prints “Strings are not equal”.

Technique 2: Check if Two Strings Are Equal with the [ Command

Here’s the script to check if two strings are equal with the [ command:

#!/bin/bash

string1="perimattic"
string2="perimattic"

if [ "$string1" = "$string2" ]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi

In this script:

– We assign the strings “perimattic” and “perimattic” to the variables `string1` and `string2`, respectively.
– Then, we use the `[` command with the equal (`=`) operator to compare the two strings.
– If the strings are equal, the script prints “Strings are equal”; otherwise, it prints “Strings are not equal”.

Technique 3 : Check if Two Strings Are Equal Using the [[ Keyword

Here’s the script to check if two strings are equal with the [[ keyword:

#!/bin/bash

string1="perimattic"
string2="perimattic"

if [[ "$string1" == "$string2" ]]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi

In this script:
– We assign the strings “perimattic” and “perimattic” to the variables `string1` and `string2`, respectively.
– Then, we use the `[[` keyword with the equal (`==`) operator to compare the two strings.
– If the strings are equal, the script prints “Strings are equal”; otherwise, it prints “Strings are not equal”.

The `[[` keyword provides more features and flexibility for conditional expressions compared to the single `[` command.

Technique4: Check if Two Strings Are Equal in One Line

[[ "$string1" == "$string2" ]] && echo "Strings are equal" || echo "Strings are not equal"

This command uses the `[[` keyword with the equal (`==`) operator to compare the two strings.

If the strings are equal, it prints “Strings are equal”; otherwise, it prints “Strings are not equal”.

The `&&` operator is used for conditional execution. If the condition (`”$string1″ == “$string2″`) is true, the first command (`echo “Strings are equal”`) is executed. Otherwise, the second command (`echo “Strings are not equal”`) is executed.

Conclusion

In conclusion, in this article we have seen different techniques comparing bash strings and how to check if the two strings are equal,.We have used the test and [commands, as well as the [[ keyword. We also explore the way to carry out these equality string comparisons in one single line by using the logical && and || operators.

Tags

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

Related articles

deepmind mNa V4J GGY unsplash

UI/UX Design, Portal Development, and End-to-End Infrastructure Deployment for Taygo Cloud

Taygo Cloud is a dynamic cloud service provider specializing in delivering scalable, efficient, and secure cloud solutions for businesses of all sizes. Their platform, [cloud.taygo.com](https://cloud.taygo.com/), offers a range of services including cloud storage, computing, and networking, aimed at helping businesses enhance their digital capabilities and streamline their operations.


✔︎ Modern infrastructure
✔︎ Consulting services

Read more
Untitled design 13

Case Study: Setting Up an Offshore Technical Development Team for Staffing Future

Staffing Future is a leading provider of innovative staffing website solutions and digital marketing strategies designed to help staffing agencies and recruitment firms enhance their online presence and optimize their recruitment processes. Known for its cutting-edge technology and comprehensive services, Staffing Future helps its clients attract and retain top talent through customized and user-friendly websites, job boards, and integrated digital marketing solutions.

Read more
Contact us

Partner with Us for Comprehensive Digital Solutions

We’re happy to answer any questions you may have and help you determine which of our services best fits your needs.

Your benefits:
What happens next?
1

We Schedule a call at your convenience 

2

We do a discovery and consulting meting 

3

We prepare a proposal 

Schedule a Free Consultation