Arithmetic operators#

Another common numeric context is conditionals with arithmetic operators, documented in the “Conditional Expressions” part of man bash. The arithmetic operators are -eq (equal), -ne (not equal), -lt (less than), -le (less than or equal), -gt (greater than), and -ge (greater than or equal). [[ "$count" -le '3' ]] is equivalent to (( "$count" <= '3' )): both sides are coerced to numbers and compared as such. The latter form should be more familiar from other languages, but there is another reason for avoiding numeric comparisons in [[: confusing numbers with strings. For example, the numeric operators coerce each argument to a number before comparing them:

You will sometimes see = used instead of == in [[ comparisons, and both are valid. Some prefer = because it’s defined in POSIX, but since most languages use = only for assignments and == only for comparisons, following the convention by using == in Bash is more universally readable.

 

This page is a preview of The newline Guide to Bash Scripting

No discussions yet