The strings in Bash can easily be compared with one another in almost the same manner as we compare the numbers in Bash. There are different operators available in Bash for string comparison.
Here at LinuxAPT, we shall look into how to use the Bash "if string equals" comparison operator.
To learn the equality comparison of the strings in Bash, you can go through the below examples:
Here, we will use the equality comparison operator in Bash to compare the string values contained inside two variables. To achieve this, you need to run the below Bash script (equals.bash):
#!/bin/bash
var1="LinuxAPT"
var2="LinuxAPT"
if [ "$var1" = "$var2" ];
then
echo "The provided string are equal"
else
echo "The provided string are not equal"
fi
You will notice that in this script, we first declare the two variables and assign them the two different strings with minor differences. Then, we use an "if-else" statement inside which we compare these two variables by using the equality comparison operator.
If these strings are equal, the "if" part of the statement is executed. Otherwise, the "else" part is executed.
You can use the below command to run this Bash script:
$ bash equals.bash
From the output, it will show that the two strings were not equal.
Here, we will use the equality comparison operator of Bash to compare a variable containing a string with another string with the following Bash script (equals.bash) :
#!/bin/bash
var1="LinuxAPT"
if [ "$var1" = "LinuxAPT" ];
then
echo "The provided string are equal"
else
echo "The provided string are not equal"
fi
Now, we only define a single variable and assign a string to it. Then, we use an "if-else" statement inside which we compared this variable with a string. If the value of this variable is equal to the provided string, the "if" part of the statement is executed. Otherwise, its "else" part is executed.
When the script is executed, you will see that the two strings were equal.
Here, we will compare our two strings. However, this time, we will use a complete sentence as our string to verify if our method works fine in this situation or not. To do this, we use the following Bash script (equals.bash):
#!/bin/bash
var1="LinuxAPT User"
var2="LinuxAPT User"
if [ "$var1" = "$var2" ];
then
echo "The provided string are equal"
else
echo "The provided string are not equal"
fi
Now, we define the two variables and assign them the two sentences as strings. Then, we simply compare these strings by making use of the equality comparison operator in Bash.
Upon the execution of this script, we figured out that the two provided strings were equal.
This implies that this method works well regardless of the length of the provided string.
This article covers the equality comparison operator for the strings in Bash. In fact, you will be able to realize that the strings can be compared in Bash very easily irrespective of their length.
Two strings are equal when they have the same length and contain the same sequence of characters.