Bash Check if Two Strings are Equal



Bash Check if Two Strings are Equal

In Bash scripting, checking if two strings are equal is useful for various tasks that require string comparison and conditional operations.


Syntax

if [ "$string1" == "$string2" ]; then
    # commands if strings are equal
fi

The basic syntax involves using the == operator within a single-bracket [ ] if statement to check if the strings are equal.


Example Bash Check if Two Strings are Equal

Let's look at some examples of how to check if two strings are equal in Bash:

1. Check if Two Strings are Equal

This script checks if the variables str1 and str2 are equal and prints a corresponding message.

#!/bin/bash

str1="hello"
str2="hello"

if [ "$str1" == "$str2" ]; then
    echo "The strings are equal."
else
    echo "The strings are not equal."
fi

In this script, the variables str1 and str2 are assigned the value 'hello'. The if statement uses the == operator to check if str1 and str2 are equal. If true, it prints a message indicating that the strings are equal. Otherwise, it prints a different message.

Check if two strings are equal in Bash

2. Check if User Input Strings are Equal

This script prompts the user to enter two strings and checks if they are equal, then prints a corresponding message.

#!/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 not equal."
fi

In this script, the user is prompted to enter two strings, which are stored in the variables str1 and str2. The if statement uses the == operator to check if str1 and str2 are equal. If true, it prints a message indicating that the strings are equal. Otherwise, it prints a different message.

Check if user input strings are equal in Bash

3. Check if Strings from Command Output are Equal

This script checks if the output of two commands stored in the variables output1 and output2 are equal and prints a corresponding message.

#!/bin/bash

output1=$(echo "test1")
output2=$(echo "test1")

if [ "$output1" == "$output2" ]; then
    echo "The command outputs are equal."
else
    echo "The command outputs are not equal."
fi

In this script, the variables output1 and output2 are assigned the result of commands that echo 'test1'. The if statement uses the == operator to check if output1 and output2 are equal. If true, it prints a message indicating that the command outputs are equal. Otherwise, it prints a different message.

Check if strings from command output are equal in Bash

Conclusion

Checking if two strings are equal in Bash is a fundamental task for string comparison and conditional operations in shell scripting. Understanding how to check for string equality can help you manage and validate strings effectively in your scripts.