Bash – Check if strings are equal ignoring case

To check if two strings are equal in Bash scripting, you can convert both the strings to lowercase, and then compare if the resulting strings are equal.

Example

In the following script, we take two strings in string1 and string2, and iterate over the individual characters in the string using a for loop.

example.sh

#! /bin/bash
 
string1="apple"
string2="AppLE"

string1_lower=$(echo $string1 | tr '[:upper:]' '[:lower:]')
string2_lower=$(echo $string2 | tr '[:upper:]' '[:lower:]')

if [ "$string1_lower" == "$string2_lower" ]; then
  echo "strings are equal ignoring case"
else
  echo "strings are not equal ignoring case"
fi

Output

sh-3.2# ./example.sh 
strings are equal ignoring case

References

Bash – Convert string to lowercase

Bash – Check if two strings are equal

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to check if two strings are equal ignoring case.