Math in Bash

This simple tutorial will show you how to do math in Bash include Integer math and floating math with some examples.

 

Integer Math

We can use expr to do some basic integer math in bash.

ARG1 + ARG2
arithmetic sum of ARG1 and ARG2
 
ARG1 - ARG2
arithmetic difference of ARG1 and ARG2
 
ARG1 * ARG2
arithmetic product of ARG1 and ARG2
 
ARG1 / ARG2
arithmetic quotient of ARG1 divided by ARG2
 
ARG1 % ARG2
arithmetic remainder of ARG1 divided by ARG2

Below are some examples:

bash-3.2$ expr 10 + 11 - 9
12
bash-3.2$ expr 7 \* 4
28
bash-3.2$ expr 99 / 11
9
bash-3.2$ expr 13 % 4
1
bash-3.2$ x=5
bash-3.2$ y=9
bash-3.2$ expr $y - $x
4
bash-3.2$ expr $y \* $x
45
bash-3.2$ expr $x + $y - 4
10

Floating point math in Bash

We can use bc(An arbitrary precision calculator language) to do floating piont math in Bash.

bash-3.2$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
3.5+4.6-2.4
5.7
 
2^3
8
 
11*8
88
 
27*2.5/3.9
17
 
scale=2
 
27*2.5/3.9
17.30
 
quit
bash-3.2$

Please be noted the variable scale is very import to the math results.

scale ( expression )
The value of the scale function is the number of digits after the decimal point in the expression.

If you need further information of bc ,just

man bc

One thought on “Math in Bash

  1. Pingback: Math in Bash

Leave a Reply

Your email address will not be published. Required fields are marked *