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.
Asked
Active
Viewed 1.9k times
1 Answers
24
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
~$

steeldriver
- 136,215
- 21
- 243
- 336
é
is not converted intoÉ
(or vice versa). – G-Man Says 'Reinstate Monica' Dec 10 '15 at 00:27var="àÉîö"
andecho "$var"
, and it correctly regurgitates the characters that I gave it, and (2) I started a new shell withLANG=fr_FR.UTF-8 bash
, and "${var^^}" and "${var,,}" still just give meàÉîö
. … (Cont’d) – G-Man Says 'Reinstate Monica' Dec 10 '15 at 21:32type foo
, it saysbash: type: foo : non trouvé
, and (b)env | grep LC_
andset | grep LC_
give no output. Can you suggest anything else to try? – G-Man Says 'Reinstate Monica' Dec 10 '15 at 21:33