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

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. Now, we will discuss the above comparison operator one by one with examples.

Compare Two Strings in Bash (==)

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.

Run the above shell script in a bash shell and check for the results. Now, change both variables’ values with different strings. Then again the script and see the results.

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:

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

Compare Strings with Regular Expression

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.

Let’s check with 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.

Run the above bash script and provide the input when prompted. Again run this script but this time input a non-numeric value and see the results.

Check if a String is Empty

While taking user input in a shell script, it’s important to check that the input string is not empty. You can use -z returns true if the string is empty.

Execute the above shell script in a bash shell and just hit enter when prompted for user input. Again run the above script and type something when prompted.

Conclusion

In this tutorial, we have discussed string comparisons in the bash script. You can also check if a string is empty or not. Also provides an example to check if the input value is a number or not.