Comparing strings is a common task when working with shell scripts, user input, or string data. In the shell, you may need to check if a value exists in another string, find if two strings have the same length, test for the beginning or end of a word, or any other type of comparison. The standard Unix tools don’t provide many options for comparing strings; the traditional lexical comparison (like checking if two words are the same length and comparing each character individually) is hard to implement efficiently in code and isn’t as valuable for a dynamic language like Bash.

Advertisement

This article explains different ways to compare strings in Bash and several related commands.

1. String Comparison Operators

We can use comparison operators with bash if statements to compare two strings. Here is the list of comparison operators to work with strings in the bash shell.

OperatorDetails
[ “string1” == “string2” ]Returns true if both strings are equal.
[ “string1” != “string”Returns true if both strings are not equal.
[ “string =~ regex ]Compare string1 with regular expression and return true matches
[ -z “string” ]Return true if the given string length is zero (0)
[ -n “string” ]Return true if the given string length is not zero

Now, we will discuss the above comparison operator one by one with examples.

2. Comparing Two Strings Are Equal?

If you need to check if two strings are equal, use the == operator. These operators compare the left operand with the right operand and return true if both match.

Let’s understand with an example. In a shell script initialize two variables with a string. Then use the if statement to compare whether both strings are equal or not using the == operator.


#!/usr/bin/env bash

STR1="TecAdmin"
STR2="TecAdmin"

if [ "$STR1" == "$STR2" ]
then
    echo "Both strings are equal"
else
    echo "Both strings are not equal"
fi

Run the above shell script in a bash shell and check for the results.

Output:
Both strings are equal

Now, change both variables values with different strings. Then again the script and see the results.

3. Check Two Strings are Not Equal (!=)

Sometimes we are required to check if both strings are not equal. You can use != operator to test if two strings are not equal. Let’s check with an example:


#!/usr/bin/env bash

STR1="TecAdmin"
STR2="HelloWorld"

##Check if both strings are not equal
if [ "$STR1" != "$STR2" ]
then
    echo "True, both strings are not equal"
else
    echo "False, both strings are equal"
fi

Run the above shell script in a bash shell and check for the results.

Output:
True, both strings are not equal

4. Compare Strings with Regular Expression

To compare strings with regular expressions in Bash, you can use the “grep” command with the “-E” (extended regex) option. The “grep” command searches a string for a pattern and returns a success exit code (0) if the pattern is found and a failure exit code (1) if the pattern is not found.

Here is an example of using the “grep” command to compare a string with a regular expression:


string="Hello world"
if echo "$string" | grep -E "^Hello"; then
  echo "Match found"
else
  echo "Match not found"
fi

We can also compare string with a regular expression in bash scripts. While using the string comparison with regular expression with an if statement, you should always enclose with [[ ]] quotes. The below example will show help you to check if the variable contains the string that begins with a specific string.


#!/usr/bin/env bash

STR="TecAdmin"

if [[ "$STR" =~ ^Tec ]]
then
    echo "Yes, the regular expression matches "
else
    echo "Regular expression not matches "
fi

Output:
Yes, the regular expression matches

Let’s check another example. In this script, we will prompt the user to input a number. Then verify whether the input value is a number or not. A number container the digits between 0 to 9.


#!/usr/bin/env bash

read -p "Input a number: " VAR

## Check if the input value is a number
if [[ "$VAR" =~ ^[0-9]+$ ]]
then
    echo "Given input is a number"
else
    echo "Sorry, input is not a number"
fi

Run the above bash script and provide the input when prompted.

First run:
Input a number: 12 Given input is a number

Again run this script but this time input a non-numeric value and see the results.

Second run:
Input a number: 1234a Sorry, input is not a number

5. Check if a String is Empty

To check if a string is empty in Bash, you can use the following syntax:


if [ -z "$string" ]; then
  echo "String is empty"
else
  echo "String is not empty"
fi

The “-z” operator is used to test if the length of the string is zero. If the length of the string is zero, the expression inside the square brackets returns true and the “then” clause is executed. If the length of the string is greater than zero, the expression returns false and the “else” clause is executed.

Conclusion

In conclusion, comparing strings in Bash is a fundamental aspect of shell scripting that can be used to make decisions, control the flow of your scripts, and process data. In this hands-on tutorial, we have covered the basics of string comparison in Bash, including the various comparison operators, syntax, and common pitfalls. We have also provided examples and exercises to help you practice and master the concepts presented in this tutorial. By following the best practices outlined in this tutorial, you can write scripts that are more robust, reliable, and efficient. Whether you are a beginner or an experienced user, string comparison in Bash is a valuable skill that can help you automate tasks, solve problems, and make the most of your shell scripts.

Share.
Leave A Reply


Exit mobile version