Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding bash *String* comparison [duplicate]

Tags:

bash

I'm trying to compare version numbers. For example, if 10.9 is less than 10.11.

Can someone please explain why this doesn't print 'yes'?

 if [[ "9" < "10" ]]; then echo yes; fi

What do I need to do to make this work correctly as clearly, 9 should be less than 10?

In addition, if I have "10.9" in a variable $VERSION, how would this be compared with "10.11", as this also fails to print 'yes'

if [[ $VERSION < "10.11" ]]; then echo yes; fi
like image 343
TheDarkKnight Avatar asked May 18 '26 10:05

TheDarkKnight


2 Answers

In this case, this will return the correct answer

if [[ "8" < "9" ]]; then echo yes; fi

But for your specific case "10" is less than "9" because 1 is less than 9. String comparison works different than numeric, so the order will be something like that

1

10

20

21

3

...

You can convert your string to numeric and use the -lt (less than) operator for numeric values. Bash values are untyped so, this will work

if [ "9" -lt "10" ]; then echo yes; fi

Some Bash reference can be found here

Be aware that "10.9" lt isn't working with a float. You can use an awk comparison for this.

if [ -n "10.1" -a -n "10.2" ]; then echo yes; fi
like image 86
Vargan Avatar answered May 21 '26 02:05

Vargan


Since < is a string comparison operator, "9" is lexicographically greater than "10". bash can only compare integers (using -lt, in which case [ "9" -lt "10 ] would be true. (Note that bash does not have separate string and integer types, only strings, meaning "9" and 9 are the exact same string. It's the operator, not the operands, that determine the behavior.)

bash does not work with floating point values at all. You need to use an external command (such as bc or awk) to compare them. Of course, if your version numbers can contain more than 1 decimal point, then you'll need to use some other approach, since they are no longer floating point numbers.

like image 34
chepner Avatar answered May 21 '26 01:05

chepner