LESSON · 1 OF 5

Arithmetic in bash

Arithmetic in bash

Bash has three ways to do integer math. One is the modern default.

$(( )): the everyday form

bash
count=5
total=$((count + 1))          # 6
half=$((count / 2))           # 2 (integer division)
mod=$((count % 3))            # 2 (modulus)
power=$((count ** 2))         # 25

$(( expression )) evaluates arithmetic and substitutes the result. Variables inside don't need $ (though it's allowed).

(( )): arithmetic evaluation without substitution

bash
count=5
((count++))                   # increment in place
((count += 10))               # count = count + 10
if (( count > 100 )); then
  echo "big"
fi

Same expression syntax, no substitution into a string. Useful for standalone math and inside if (nicer than [ "$x" -gt 100 ]).

Operators

+  -  *  /  %  **       arithmetic
++ --                    increment / decrement
== != < <= > >=          comparison
&& || !                  logical
&  |  ^  ~  << >>        bitwise
= += -= *= /= %=         assignment

All C-style. = inside (( )) is assignment, not comparison (that's ==).

The old ways: let and expr

You'll see these in older scripts:

bash
let "count = 5 + 1"           # older style, works but $((...)) is clearer
count=$(expr 5 + 1)           # very old, spawns a subprocess for every calculation

Use $(( )) and (( )) for new scripts. Avoid expr (slow) and let (older style, easier to get wrong).

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute