Checking strings

You can use the if command with the test command to check if the string matches a specific criterion:

The less than and greater than should be escaped with a backslash as if it shows a warning.

Let's see some examples to explain how if statements work:

#!/bin/bash 
if [ "mokhtar" = "Mokhtar" ]  
then 
echo "Strings are identical" 
else 
echo "Strings are not identical" 
fi 
 

This if statement checks if strings are identical or not; since the strings are not identical, because one of them has a capital letter, they are identified as not identical.

Note the space between the square brackets and the variables; without this space it will show a warning in some cases.

The not-equal operator (!=) works the same way. Also, you can negate the if statement and it will work the same way, like this:

if ! [ "mokhtar" = "Mokhtar" ]

The less-than and greater-than operators check if the first string is greater than or less than the second string from the ASCII-order perspective:

#!/bin/bash 
if [ "mokhtar" \> "Mokhtar" ]  
then 
echo "String1 is greater than string2" 
else 
echo "String1 is less than the string2" 
fi 
 

In the ASCII order, the lower-case characters are higher than the upper case.

Don't get confused if you use the sort command to sort a file or similar, and find that the sorting order works the opposite way to the test command. This is because the sort command uses the numbering order from the system settings, which is the opposite to the ASCII order.

To check the string length, you can use the -n test:

#!/bin/bash 
if [ -n "mokhtar" ]  
then 
echo "String length is greater than zero" 
else 
echo "String is zero length" 
fi 

To check for a length of zero, you can use the -z test:

#!/bin/bash 
if [ -z "mokhtar" ]  
then 
echo "String length is zero" 
else 
echo "String length is not zero" 
fi        
 

We have used quotes around the tested strings, even though our string has no spaces.

In case you have a string with spaces, you MUST use quotes.