How to compare string in Bash?

Bash Shell empowers system administrators to compare string. It provides six different operators using which you can check equality, inequality, and other string related comparisons. In Bash Shell, 0 is considered True and non-zero value is considered False. Following table describes these operators in great detail:

String Comparison Operators Description
[ string1 = string2 ] returns True if both string1 and string2 are same.
[ string1 == string2 ]
[ string1 != string2 ] returns True if both string1 and string2 are not same.
[ string1 \> string2 ] returns True if string1 is greater than string2
[ string1 \< string2 ] returns True if string1 is less than string2.
[ -n string1 ] returns True if the length of the string is greater than zero.
[ string ]
[ -z string1 ] returns True if the length of the string is zero.
For checking whether string is null or not.
[ -n "string" ] returns True if a string is not null.
[ "string" ]
[ -z "string" ] returns True if a string is null.

Note: You must escape greater-than and less-than symbol while comparing string otherwise they will be treated as redirection symbols. To check whether string is null or not, you must enclose string within double quotes. Spaces must be present after the [ and before the ]

In addition to this, Bash shell also offers another way of comparing strings which is using double square brackets like this: [[ condition ]]

Note: If you are comparing string inside [[...]] then there is no need to escape greater than and less than operators. Also, there must be a space after the [[ and before the ]].

How to check if string is empty or not in Bash?

str="Android"
if [ -z $str ]
then
  echo "str variable is empty."
else
  echo "str variable is not empty."
fi

Output

str variable is not empty.

How to check if strings are equal or not equal in Bash?

password="123456"
read -s -p "Enter a password: " pass
echo
if [ $password == $pass ]
then
  echo "Both passwords are same."
else
  echo "Both passwords are not same."
fi

Output

Enter a password:
Both passwords are same.

How to check if a string is null or not in Bash?

str1=
if [ -z "$str1" ]
then
  echo "string is null."
else
  echo "string is not null."
fi

Output

string is null.

How to check if one string is greater than another string in Bash?

if [ "Mango" \> "Apple" ]
then
  echo "Mango is called the king of fruits."
else
  echo "An apple a day keeps the doctor away."
fi

Output

Mango is called the king of fruits.

Recommended Posts