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}".
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate