Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

My search this morning was about how could I compare two decimal numbers in bash, and I came to this answser: How to compare to floating point number in a shell script. This one, however, doesn't include this answer here:

$ [[ ((3.56 < 2.90)) ]]; echo $?
1
$ [[ ((3.56 < 4.90)) ]]; echo $?
0

Considering that answer has been downvoted, and it looks some kind of unusual bashism, is this arithmetic evaluation trustworthy for accuracy?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

bash does not understand floating point numbers.
Quoting bash manual page, section ARITHMETIC EVALUATION:

Evaluation is done in fixed-width integers […].

So ((3 < 4)) or ((3 < 2)) are actually correct arithmetic expressions. You can type the following:

$ echo "$((3 < 4)) -- $((3 < 2))"

output: 1 -- 0

But $ echo $((3.3 < 3.6)) will return a syntax error message. In your example, you are actually comparing strings. Hence some example:

$ [[ ((3.56 < 04.90)) ]]; echo $?

output: 1

share|improve this answer
    
s/flotting/floating/ –  Josh The Geek Jun 14 at 21:12
    
Oh thanks :) Bad reflex due to my native language I suppose. I'll correct it immediately. –  Qeole Jun 14 at 21:55
    
Both answers are awesome, but I'm choosing yours because of the example, which made me realize what could go wrong :) –  Teresa e Junior Jun 15 at 4:16

Inside [[...]] < is for string comparison.

So [[ 3.56 < 2.90 ]] or [[ (3.56 < 2.90) ]] or [[ ((3.56 < 2.90)) ]] or [[ (((3.56 < 2.90))) ]]... is just comparing the 3.56 string with the 2.90 string.

For integer comparison, it's [[ 3 -lt 2 ]] or (( 3 < 2 )). If you want floating point comparison, you need ksh93 or zsh; bash can't do it.

share|improve this answer
2  
To illustrate the importance of the difference between string vs. numeric comparison, consider that [[ 11.56 < 2.90 ]] (and [[ ((11.56 < 2.90)) ]] and...) is true, because "1" comes before "2" in ascii sorting order. –  Gordon Davisson Jun 15 at 0:51
1  
@GordonDavisson, yes, and [[ 0.1 < 1e-20 ]] and whether [[ -2 < 1 ]] is locale-dependent. –  Stéphane Chazelas Jun 15 at 9:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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