User Tools

Site Tools


2018numeric_cmp

This is an old revision of the document!


Comparison operators in BASH

The multiple constructs that are available in BASH can lead to confusion. To distinguish numeric versus alphanumeric comparisons (sorting strings, like filenames), follow these rules:

  • To compare values numerically, you can use the flag operators -lt (less than),-gt (greater than), -eq (equal to), -ne (not equal), -ge (greater or equal to), -le (less than or equal to):
    • With single brackets [ ]
    • With double brackets [[ ]]

For example, say a=2 and b=10:

  • [ $a -lt $b ] is TRUE
  • [[ $a -lt $b ]] is TRUE
  • [[ $a -ge $b ]] is FALSE

What results in an alphanumeric comparison (which you don't want), or a syntax error (which you might not see) is the following:

  • [[ $a < $b ]], alphanumerically FALSE
  • [ $a < $b ], error; also FALSE.

Alternatively, a numeric comparison is valid with parentheses:

  • (( $a < $b )) is TRUE

It can be difficult to keep track of which constructs are OK in different situations, but here are some rules in BASH:

  • [ expr ], expr is evaluated as BASH command syntax, which has special meaning for some of the symbol operators.
  • [[ expr ]], a “safer” alternative to the single brackets, as there is less command parsing
  • (( expr )), expr is assumed to contain the symbol operators.

Testing is very important. To distinguish between the correct, incorrect, and error-producing constructs, I wrote a script that produces this table:

Syntax Output Error
Numeric comparisons: 2 less than 10 should be TRUE
[ 2 < 10 ] FALSE 10: No such file or directory
[ 2 \< 10 ] FALSE
[[ 2 < 10 ]] FALSE
[[ 2 -lt 10 ]] TRUE
[ 2 -lt 10 ] TRUE
[ "2" -lt "10" ] TRUE
test 2 -lt 10 TRUE
(( 2 < 10 )) TRUE
(( 2 -lt 10 )) FALSE ((: 2 -lt 10 : syntax error (error token is "10 ")
Numeric comparisons: 10 less than 2 should be FALSE
[ 10 < 2 ] FALSE 2: No such file or directory
[ 10 \< 2 ] TRUE
[[ 10 < 2 ]] TRUE
[[ 10 -lt 2 ]] FALSE
[ 10 -lt 2 ] FALSE
test 10 -lt 2 FALSE
(( 10 < 2 )) FALSE
(( 10 -lt 2 )) FALSE ((: 10 -lt 2 : syntax error (error token is "2 ")
2018numeric_cmp.1536346155.txt.gz · Last modified: 2018/09/07 12:49 by david