I know we should use =
(or its alias ==
) to compare strings in Bash. But I forgot about it and used -eq
in a script, getting strange results, but no error.
I haven’t found any documentation regarding this but from my tests, [[ "$foo" -eq "$bar" ]]
appears to always evaluate to 0
, i.e. success, for any value of $foo
or $bar
, provided they don’t start with a digit:
$ [[ "1" -eq "1" ]] && echo yes || echo nope
yes
$ [[ "1" -eq "0" ]] && echo yes || echo nope
nope
$ [[ "x1" -eq "0" ]] && echo yes || echo nope
yes
$ [[ "x1" -eq "x0" ]] && echo yes || echo nope
yes
$ [[ foo -eq bar ]] && echo yes || echo nope
yes
$ [[ so -eq different ]] && echo yes || echo nope
yes
It does evaluate to 1
(error) when one value starts with a digit:
$ [[ 1x -eq 1 ]] && echo yes || echo nope
bash: [[: 1x : valeur trop grande pour la base (le symbole erroné est "1x")
nope
The error message I get is French for "value too high for the base (the erroneous symbol is "1x"".
Why doesn’t it return 1
and/or show an error when getting a non-number? It makes things really hard to debug when you made that mistake.
I used GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu).