Interview Prep/Shell Scripting/Variables, quoting and expansions

How does arithmetic work in Bash?

BeginnerConceptVariables, quoting and expansions
Answer

Bash does integer arithmetic only, in $(( )) (expands to the result) and (( )) (a command whose exit status is 0 if the result is non-zero).

used=$(( total - free ))
pct=$(( used * 100 / total ))       # integer division, truncates
(( pct >= 90 )) && echo critical
(( retries++ ))                     # careful under set -e when retries=0
echo $(( 2 ** 10 )) $(( 17 % 5 ))   # 1024 2

Variables inside (( )) need no $. For decimals use awk or bc: awk "BEGIN {printf \"%.2f\", $a/$b}".

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions