BASH Programming

How Do I Compare Two String Variables in an ‘If’ Statement in Bash?

When writing Bash scripts, it’s common to compare string variables to check for certain conditions. However, comparing strings in Bash can be tricky, especially when dealing with variables that contain spaces or special characters. This article will discuss the different ways of using the by using an ‘if’ statement in Bash to compare two string variables in shell script.

How Do I Compare String Variables Using the ‘==’ Operator

The simplest way to compare two string variables in Bash is to use the ‘==‘ operator in an ‘if‘ statement. The ‘==‘ operator compares two strings for equality and if both the strings are the same it will return true, here is an example code that uses this operator to compare two strings:

#!bin/bash
name1="Mark"
name2="Jhon"

if [ "$name1" == "$name2" ]; then
  echo "The names are the same."
else
  echo "The names are different."
fi

Here we are comparing two string variables ‘name1‘ and ‘name2‘. The ‘==‘ operator checks if both strings are equal and if they are, it prints “The names are the same.” Otherwise, it prints “The names are different.” Note that we have enclosed the variables in double-quotes to ensure that the comparison works even if the variables contain spaces or special characters.

How Do I Compare String Variables Using the ‘!=’ Operator

In addition to the ‘==‘ operator, Bash also provides the ‘!=‘ operator to compare two strings for inequality. The ‘!=‘ operator returns true if the strings are different and here’s an example:

#!bin/bash
code1="7845"
code2="9632"

if [ "$code1" != "$code2" ]; then
  echo "The codes are different."
else
  echo "The codes are the same."
fi

Here we are comparing two string variables ‘code1‘ and ‘code2‘. The ‘!=‘ operator checks if both strings are different and if they are, it prints “The codes are different.” Otherwise, it prints “The codes are the same.

Conclusion

Comparing string variables in Bash can be done using various operators such as ‘==‘ and ‘!=‘. These operators are used in an ‘if‘ statement to check for certain conditions. By knowing how to compare string variables, we can write more robust and efficient Bash scripts.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.