Arithmetic conditions

The POSIX specification for the test and [ commands includes a few arithmetic tests for integers:

  • [ "$a" -eq "$b" ]: Equal
  • [ "$a" -ne "$b" ]: Not equal
  • [ "$a" -lt "$b" ]: Less than
  • [ "$a" -le "$b" ]: Less than or equal to
  • [ "$a" -gt "$b" ]: Greater than
  • [ "$a" -ge "$b" ]: Greater than or equal to
Be careful not to confuse -lt and -gt with < and >; the latter are lexicographic tests, to see whether strings sort after one another. For example, [ 2 \> 10 ] exits successfully, because the "10" string sorts after "2"!

Sometimes using these tests with expansion of arithmetic expressions can be unwieldy to write; for example, if we wanted to test whether the value of the bytes variable, divided by 1,000, was greater than ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.