Command to Compare Two Strings

Command to Compare Two Strings

I need to compare two strings and ignoring the case of the contents. IF [ $first != $second ]. Anything I can add to this command so that the comparison ignores the case.

1 Answer

In bash, you can perform case conversions easily e.g. if var="vAlUe" then

$ echo "${var^^}"
VALUE

while

$ echo "${var,,}"
value

You can use this to make you comparison case-insensitive by converting both arguments to the same case, i.e.

if [ "${first,,}" == "${second,,}" ]; then
  echo "equal"
fi

or

if [ "${first^^}" == "${second^^}" ]; then
  echo "equal"
fi

Another approach is to use the bash nocasematch option (thanks @Tshilidzi_Mudau), although this appears to work only with the [[ ... ]] extended test operator:

$ first=abc; second=ABC
$ (shopt -s nocasematch; if [[ "$first" == "$second" ]]; then echo "Match"; else echo "No match"; fi)
Match

but

$ (shopt -s nocasematch; if [ "$first" == "$second" ]; then echo "Match"; else echo "No match"; fi)
No match
~$ 
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.