Hacker News new | ask | show | jobs
by usr1106 572 days ago
So -eq triggers evaluation? Sounds like typical bash magic. I would use [ an the problem goes away.

Showing -eq is not the best example, it can just be replaced by = and the problem goes away.

But if you need -gt or similar there is no replacement. So one should stick to [.

If I follow correctly the dangerous combination is [[ and arithmetic comparisons?

1 comments

`-eq` is for arithmetic comparison; `=` is for string comparison. They don't do the same thing, and it's unsound to uniformly replace either with the other.

The dangerous thing here is that an undefined number of contexts exist where Bash treats strings as arithmetic expressions, which can contain arbitrary code despite not being quoted for expansion. `-eq` is just one example of that; others have linked other examples.

(This is all for case #1. With case #2, `[` and `test` are also susceptible so long as their builtin variants are used.)

Can you give an example where = would be unsuitable for comparison of numbers?
Here's a trivial one:

    $ [[ 0xFF -eq 255 ]] ; echo $?
    0

    $ [[ 0xFF = 255 ]] ; echo $?
    1
Oh, hex. Another bashism. Not sure when I would have needed that in a shell script last time. So in most cases just using [ solves the problem. If you want to use hex from untrusted user input you need to validate the input first. Yes, the bash programmer needs to be aware of many pitfalls. I wasn't, but I would call myself more a bash avoider than a bash programmer. Yes, I use bash for interactive use, talking only about scripting.