How To Use Arithmetic Tests With Conditional Expressions In Bash

Pavol Kutaj
2 min readDec 11, 2021

--

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.

1. Notes

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

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com