In any programming language, the task of comparing strings is generally required. For example, you need to take the user input for the password, phone number, email etc. and then need to compare it with the value saved in the database. Show Similarly, you may be using the case statement and upon entering a value, you need to match a pattern and perform the action based on matched string etc. Bash also provides ways of comparing string and this is the topic of this tutorial. In the following section, I will show you ways and examples of how to compare strings in Bash Shell scripting. The examples include:
See the examples with the code below. An example of comparing strings in Bash by == operatorIn this example, we will check the equality of two strings by using the “==” operator. For that, we have two string variables and check the values in the if condition. If both strings are equal, the equality message is displayed:
The output:
What if the case of a string was different?Using the same word in both strings as in the above example, except for I changed the letter “b” to “B” for the first string. See the code and output:
The result:
So, as using the “==” operator, keep in mind that the strings are compared with case-sensitivity. So, how to perform case-insensitive comparison?As you may not control user inputs and you want to perform case insensitive comparison, you may use the nocasematch feature provided by Bash. I am using the same example as in the above case and just added the following line:
The example script:
and the output now is:
Using the != operator for in-equalityYou may also use “Not equal to” operator i.e. “!=” to compare strings. The example below shows using the “!=” operator:
The output:
The example of checking a string is emptyIn certain situations, you may require checking a string variable is empty or not before processing further or taking some action based on that variable. By using “-z” operator, you may check if a string is empty or not. In the example below, I declared a variable with empty value and then checked its value in the if condition with -z operator: The code:
The output:
As string variable is empty, so –z returned True and the statement is executed in the if condition. How to use –n operatorSimilarly, the “-n” operator checks if a string is non-empty. It returns true if a given string is not empty. The example below shows its usage:
The output: The variable contains some text. |