DevOps

Bash String Comparison

Bash string comparison guide.

Introduction

Bash is a Unix shell and command-line language used by default in most Linux distributions. Using Bash, developers can create scripts to perform various actions, including string comparison.

String comparison includes comparing the value of two strings – their length or sequence of characters. Compare strings when checking for certain conditions before proceeding to the next step of the script.

This tutorial will teach you how to compare strings using a Bash script.

Bash string comparison guide.

Prerequisites

Bash Strings Comparison Operators

Unlike some standard programming languages, Bash has no built-in comparison functions, which means users need to use comparison operators. Comparison operators compare the values of input strings and output a TRUE or FALSE value.

Note: Apart from Bash, Linux has other useful text manipulation and processing tools, such as the sed editor, awk command, grep command, or the sort command.

Some of the most commonly used string comparison operators are listed in the table below:

Operator Description
[str1] = [str2] The equality operator returns TRUE if both operands are equal. Used with the [ command.
[str1] == [str2] The equality operator returns TRUE if both operands are equal. Used with the [[ command.
[str1] != [str2] The inequality operator returns TRUE if the specified operands are not equal.
[str1] =~ regex The regex operator returns TRUE if the specified [str1] string matches the extended regex.
[str1] > [str2] The “greater than” operator returns TRUE if [str1] is greater than [str2] based on lexicographical order.
[str1] < [str2] The “less than” operator returns TRUE if [str1] is smaller than [str2] based on lexicographical order.
-z [string] Returns TRUE if the string length is 0.
-n [string] Returns TRUE if the string length is not 0.

When comparing strings, make sure to:

  • Use a blank space between the binary operator and the operands.
  • Use double quotes around variable names. Not specifying double quotes causes word splitting or globbing issues.

Note: Bash also allows == to be used for equality with [ , but this is not the standard usage.

Bash Strings Comparison Examples

Different operators offer different ways of comparing strings, depending on the requirement.

Below are examples of common ways of using comparison operators for string comparison in Bash. In the examples below, we use Bash scripts which allow users to save a function and reuse it whenever necessary.

Check if Strings are Equal

Use the = or == operators when checking if strings are equal. Follow the steps below to create a Bash script and compare two strings:

Check Predefined Strings

1. Open the terminal (Ctrl + Alt + T) and create a new Bash script. We will use the vi/vim text editor:

vi script1.sh

2. Enter the following code:

#!/bin/bash
str1="Phoenix"
str2="NAP"
if [ "$str1" = "$str2" ]; then
    echo "The strings are equal."
else
    echo "The strings are different."
fi
  • The script contains two variables (str1 and str2) that are already defined.
  • The script utilizes the if statement and the = operator with the [ command. The if statement either proceeds with the first clause or the else clause, depending on whether the strings are equal or not.

3. Save the script and exit vi:

:wq

4. Run the Bash script:

bash script1.sh
Checking strings for equality using Bash.

The script outputs that the two strings are different.

Check Input Strings

Alternatively, use the == operator with the [[ command, which takes input from the user and then compares the specified strings.

1. Enter the following lines:

#!/bin/bash
read -p "Enter the first string: " STR1
read -p "Enter the second string: " STR2
if [[ "$STR1" == "$STR2" ]]; then
   echo "The strings are equal."
else
   echo "The strings are different."
fi

2. Run the script to test the code:

Checking strings for equality.

The script first prompts for the two strings and then outputs the result.

Note: The read command prompts the user for input. Without it, you must specify the variables within the script.

Check if Strings are Different

The != inequality operator allows users to test if two strings are not equal. Follow the steps below to test the operator.

1. Create a script with the following code:

#!/bin/bash
str1="data"
str2="server"
if [ "$str1" != "$str2" ]; then
   echo "The strings are different."
else
   echo "The strings are the same."
fi

2. Run the script:

Checking if strings are different.

The two strings are different, which is stated in the result.

Check for Substrings

A substring is a contiguous sequence of characters within a string. For example, NAP is a substring of the phoenixNAP string.

There are two ways to check for a partial value in a string (i.e., if a string contains a substring):

Replace Characters With Asterisk

Use the asterisk (*) symbol to replace characters in the specified substring. The asterisk is a wildcard character allowing users to perform partial matching. Follow the steps below to use partial matching when comparing strings:

1. Create a new Bash script and enter the following lines:

#!/bin/bash
VAR='Welcome to phoenixNAP!'
if [[ $VAR == *"NAP"* ]]; then
  echo "The string contains the NAP substring."
else
  echo "The string doesn't contain the specified substring."
fi

2. Run the script:

Checking for substrings using the asterisk.

The output states that the specified substring is a part of the string.

Use the Regex Operator

Another way to check for substrings is to use the =~ regex operator. Follow the steps below:

1. Create a Bash script and enter the lines below:

#!/bin/bash
VAR='Welcome to phoenixNAP.'
if [[ $VAR =~ .*topho.* ]]; then
  echo "The substring exists."
else
  echo "The string doesn't contain the specified substring."
fi
  • The .* surrounding the specified substring matches zero or more occurrences of any character, except a newline character.

2. Run the script:

Checking for substrings using the regex operator.

The command states that the substring is not a part of the specified string since the blank space was omitted.

Check for Empty Strings

Bash also allows users to check if a variable is an empty string or not. Check for empty strings using the -n and -z operators. Follow the steps below to create an example script for each operator:

The -z Operator

Search for empty strings with the -z operator by following the steps below:

1. Create a new Bash script and copy the lines below:

#!/bin/bash
VAR=''
if [[ -z $VAR ]]; then
  echo "The string is empty."
fi

2. Save and run the script:

Checking for empty strings.

The script states that the string is empty. When the string is not empty, there is no output. To provide an output if the string is not empty, specify the else condition in the script, like in the example below.

The -n Operator

1. Create a new script and enter the lines below:

#!/bin/bash
VAR='phoenixNAP'
if [[ -n $VAR ]]; then
  echo "The string is not empty."
else
  echo "The string is empty."
fi

2. Run the Bash script and check the result:

Checking for empty strings using the -n operator.

The script tests the $VAR variable and outputs that the string is not empty.

Comparing Strings with Case Statements

The Bash case statement is a form of the if elif else conditional statement, simplifying complex conditions and offering multiple choices. When using the case statement, there is no need to specify the test operators for comparing strings. However, the statement only matches the string against specified patterns.

Follow the steps below to create an example case statement:

1. Create a new Bash script and enter the following lines:

#!/bin/bash
shopt -s nocasematch
echo "Enter an OS name: "
read VAR
case $VAR in
Windows)
   echo -n "The OS is Windows."
   ;;
Fedora | Debian | Ubuntu | Android)
   echo -n "The OS is Linux-based."
   ;;
esac
  • The shopt command makes pattern matching case insensitive.
  • The script compares the input variable $VAR against the patterns in each clause until a match is found.
  • The pipe symbol | separates multiple patterns in a clause.

2. Run the script and enter a string to test if it works:

Comparing strings using a Bash case statement.

The script compares the input string to the predefined strings and outputs the appropriate message based on its findings.

Lexicographic Comparison

Lexicographic comparison is the alphabetical comparison of two strings. The characters in each string are converted to Unicode and their value compared sequentially from left to right. The comparison starts from the first character of strings until the NULL character is found.

Use the less than (<) and greater than (>) operators to compare strings lexicographically.

Follow the steps below to create an example script for lexicographic comparison:

1. Create a new script and enter the following lines:

#!/bin/bash
str1="after"
str2="later"
if [[ "$str1" > "$str2" ]]; then
  echo "$str1 is greater than $str2."
else
  echo "$str2 is greater than $str1."
fi

2. Save and run the script:

Comparing strings lexicographically in Bash.

In the example above, we compare the strings After and Later. For example, lexicographically, L is treated as greater than A because the L Unicode character is U+004C, which is greater than that of the letter A – U+0041. Therefore, the string Later is evaluated as greater than After.

Note: Read about bash eval, a command used to evaluate and execute strings as a shell command.

Conclusion

This tutorial showed the basics of string comparison in Bash scripting.

For more Bash tutorials, see how to comment in Bash, learn to use the Bash wait command, check if a file exists using Bash, or customize the Bash prompt.

Đăng ký liền tay Nhận Ngay Bài Mới

Subscribe ngay

Cám ơn bạn đã đăng ký !

Lỗi đăng ký !

Add Comment

Click here to post a comment

Đăng ký liền tay
Nhận Ngay Bài Mới

Subscribe ngay

Cám ơn bạn đã đăng ký !

Lỗi đăng ký !