2

While reading through a bash style guide I found the following guideline:

Math / Integer Manipulation

Use ((...)) and $((...)).

a=5
b=4

wrong

if [[ $a -gt $b ]]; then ... fi

right

if ((a > b)); then ... fi

When I inquired about the reasoning I was told that the [[ test could potentially choke trying to compare numbers with leading zeros. In my testing I have not been able to recreate this issue.

My Question

Is there actually a functional difference between ((a > b)) and [[ "$a" -gt "$b" ]]?

jesse_b
  • 37,005

1 Answers1

4

Not that I can see.

But there is a difference between [[ val1 < val2 ]] and (( val1 < val2 )): the former is a string comparison.

$ [[ 2 -lt 007 ]] && echo true || echo false
true
$ [[ 2 < 007 ]] && echo true || echo false
false
$ (( 2 < 007 )) && echo true || echo false
true

Though leading zeroes are still a problem in both cases:

$ (( 20 < 021 )) && echo true || echo false
false
$ [[ 20 -lt 021 ]] && echo true || echo false
false

That's because they mark octal numbers, as in C. But you prevent that by prefixing them with 10#. (Bash Reference 6.5 Shell Arithmetic)

$ (( 10#20 < 10#021 )) && echo true || echo false
true
ilkkachu
  • 138,973
  • 1
    @fpmurphy1, Well, I don't think I'm that interested in continuing this argument. You can post your own answer to argue your point, if you wish. – ilkkachu Dec 22 '17 at 18:20