user321627
user321627

Reputation: 2572

"-eq" operator always rings true for string comparisons between double brackets

For example:

A="T"
if [[ $A -eq "M" ]]; then
    echo "$A"
fi

this will always echo T.

Upvotes: 1

Views: 87

Answers (1)

oguz ismail
oguz ismail

Reputation: 50785

-eq is meant for integer comparisons. And between [[ and ]], if operands around -eq (and -ne, -lt, etc.) are not integers but valid variable names, bash assumes these are variables and tries to dereference them (recursively). In that same context, an unset/empty variable's value is considered to be zero; so, you're basically comparing 0 to 0 there. See this transcript:

$ unset A M T
$ A="T"
$ if [[ $A -eq "M" ]]; then
>     echo "$A"
> fi
T
$
$ T="1"
$ A="T"
$ if [[ $A -eq "M" ]]; then
>     echo "$A"
> fi
$

When T is assigned a number other than zero, it doesn't ring true anymore.

For further information, refer to:

Upvotes: 3

Related Questions