bash how to do math


You can use arithmetic expansion with parentheses or square brackets:

echo $((a+5))

Output: 5

echo $[a+2]

Output: 2

Another option is using the command "bc":

echo "5+3" | bc

Output: 8

If you need to do math with a float numbers, use the variable "scale" to define how operations use decimal numbers

echo "scale=2; 1/4" | bc

Output: 0.25

Evaluate expression with only integer you can use the command "expr"

echo `expr 10 - 2`

Output: 8

Be careful with multiply operation. Always escape * (asterisk) char with \. For example:

expr 5 \* 3

Output: 15

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.