1

This question already has an answer here:

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" ]]?

marked as duplicate by don_crissti, Community Dec 22 '17 at 17:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

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
  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.