mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
6.99k stars 333 forks source link

interp: some binary tests should use space trim before atoi #928

Closed ihar-orca closed 1 year ago

ihar-orca commented 1 year ago

It seems that the Bash trims spaces before integer comparison:

> if [ " 14 " -lt "22" ]; then  echo "true"; fi
< true

> if [ " 14 " -eq "14" ]; then  echo "true"; fi
< true

The sh/interp uses strict comparision rules and does not use any space trim functions before the binary tests that are defined in interp/test.go (binTest func, atoi).

mvdan commented 1 year ago

Thanks for reporting. Want to send a PR? We should check other forms of arithmetic expressions too, like let x=" 3 " or your example with [[ as well.

ihar-orca commented 1 year ago

no, currently I don't have any relevant and correct PR. for the local issue I just made a call for strings.TrimSpace inside each atoi but I think it's not the best idea.

mvdan commented 1 year ago

For the record, this is a simple form of https://github.com/mvdan/sh/issues/754. When it comes to arithmetic expressions, we don't expand quoted strings into fields. If we did that, then the spaces would go away in your example.

That said, this scenario is indeed easy to solve with TrimSpace, so it seems fine to me. cc @riacataquian