BC

  • The bc command acts like a calculator.

  • It is usually used to set variables, using echo, pipe and backquotes.
  • Use the -l option to get accurate floating-point arithmetic.

  • Example:
    $ a=2;
    $ a=`echo "3 * $a + 1" | bc -l`;
    $ echo $a
      7

  • Note: the double quotes stop the * being used as a wildmask for filenames.
  • Numerical comparisons of non-integers can be done with bc where 0 is returned for false and 1 for true.
      e.g.   echo "-1.2 < 0.5" | bc gives 1
      e.g.   echo "-1.2 > 0.5" | bc gives 0
    So in an if statement do something like:
      if [ `echo "$a < $b" | bc -l` = 1 ] ; then ...