Bash How to do Math

Bash How to do Math

You can use arithmetic expansion with parentheses or square brackets:

a=0
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 number, 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 operations. Always escape * (asterisk) char with \. For example:

expr 5 \* 3

Output: 15

Leave a Comment