How To Use Arithmetic Tests With Conditional Expressions In Bash

The aim of this page📝is to show how numbers are tested in bash conditional expressions [[ <exp> ]] ...which is different from testing files and strings.

My impression is that neither Powershell nor python have this level of complexity and are much more uniform, almost kinder to work with. Bash has lots of tradition attached to it, almost like a natural language where things could be easier, but since you need to communicate and you need compatibility with others, you are stuck with conventions.

VAR     | MEANING
--------|--------------------------------------------------
$# | count of args
${#var} | length of the variable
$? | exit command value for the last command you wrote
  • you can only compare ints because bash does not handle floats at all
  • syntax has special operators
[[ <arg1> OP <arg2> ]]
  • important: in conditional expressions, do not use regular operators such as =, <, > on numbers
  • in conditional expressions, these work only with strings
STRING1 = STRING2
True if the strings are equal.
STRING1 != STRING2
True if the strings are not equal.
STRING1 < STRING2
True if STRING1 sorts before STRING2 lexicographically.
STRING1 > STRING2
True if STRING1 sorts after STRING2 lexicographically.
  • whereas
arg1 OP arg2   Arithmetic tests.  OP is one of 

OP | MEANING
----|----------------------
-eq | equal
-ne | not equal
-lt | less than
-le | less or equal than
-gt | greater than
-ge | greater or equal than
  • in arithmetic expressions (( <exp> )) or C-style for loop definitions, you actually can use regular operators on numbers
>>> (( 5 > 4 )) && echo "five is greater than four"
five is greater than four

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com