Doing math with bash
18 Aug 2015bash can be used to perform simple arithmatic when needed. It is only limited to integer mathematics though. You can see this by using the expr.
An excerpt about expr
from the link above:
All-purpose expression evaluator: Concatenates and evaluates the arguments according to the operation given (arguments must be separated by spaces). Operations may be arithmetic, comparison, string, or logical.
Some trivial example usage shows that you can get some quick results if you only need integer math.
At this point, you could probably go for the full-nuclear option and get perl or python to perform floating point calculations; but to keep things a little more shell oriented, you can go with a lighter-weight option, bc.
bc
is an arbitrary precision calculator language. Much like every other good shell tool, you can invoke it so that it’ll take its input from STDIN
and return its output to STDOUT
. Here are some example invocations:
You can see that if you want precision on your answers from integer inputs, you’ll need to set the scale
variable to suit. Only feeding in static values is a bit basic though. To put this to work, you just need some variable data at hand.
What’s the percentage battery left on this notebook?
Not much!