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.

Brackets

  • Single brackets [ ] are generally OK, but might confuse some syntax as commands (thus causing errors)
  • Double brackets [[ ]] have less parsing, so are generally safer to use.

Correct Numeric Comparisons

You must use the flag operators, or the symbolic operators inside double parentheses to correctly compare values numerically. For example, say a=2 and b=10:

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

Incorrect Numeric Comparisons (lexicographic order)

What results in an alphanumeric comparison (which has unexpected behavior), or a syntax error (which you may overlook) is the following:

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

Importance of Testing

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.1536347191.txt.gz · Last modified: 2018/09/07 13:06 by david