· df · 1 min read

Arithmetic/Math calculations using shell script & Perl

Technology

Unix Shell scripts are perfect when it comes to simple automation tasks. But the in-built calculations are quite poor compared to rest of its functionality. The main issues I've faced using out-of-box shell script functions like expr, bc, echo are

  • Unable to calculate decimal places correctly

  • Error handling very poor (even divide by 0) and goes out of control.

  • Hard to control precision

  • Escape characters and regex increases complexity with formula

Object Oriented programs like Java/Python/.NET are excellent for arithmetic calculations. But this involves another level of coding and program installation. The trick I used is to use PERL which is built in almost all *nix distributions. Some of the advantages of using PERL within shell script are

  • Easy to embed Perl commands into shell scripts

  • Most of *nix distro have PERL inbuilt

  • Reduced regex or escape character usage

  • Can put formulae into config file and can loop them into the shell script

  • precision, error handling are much better

How to do math calculations in shell scripts


  • Write your shell script and put a function to do the real formula calculation

  • Use perl command line (-e) within shell script

perl -le 'printf "%.0f", eval"@ARGV"' "($VAL2-$VAL1)"

The above calculation will subtrace $VAL1 from $VAL2 and print with no decimal places (0f). The precision can be easily manipulated by changing the printf