Notes on "bc"

Contents

Useful command line options

-s,--standard  Adhere to the POSIX standard
-l,--mathlib   Add a math library, set SCALE to 20

Variables

  • Names begin with a letter and may be followed by [[:alnum]_]*
  • Four special variables:
  • SCALE defines how some operations use digits after the decimal point
  • IBASE is the conversion base for input numbers
  • OBASE is the conversion base for output numbers
  • LAST is a variable that has the value of the last printed number (an extension)
  • Output is generated by deliberately not assigning the result of a calculation to a variable.

Comments

bc uses /* ... */ style comments. As an extension, # is a commment if it’s a the start of a line (after whitespace)

Operators

Directly from the Wikipedia page

+     -     *     /
+=    -=    *=    /=
++    --    <     >
==    !=    <=    >=
( )   [ ]   { }

Modulus operators % and %= work, but SCALE should be set to 0 first.

Using “bc” in the shell

PI=”$(echo “scale=20; 4*a(1)” | bc)” echo $PI

Functions

Built-in:

  • sqrt()

From the library:

  • s(x) - sine
  • c(x) - cosine
  • a(x) - arctangent
  • l(x) - natural logarithm
  • e(x) - exponential funtions
  • j(n,x) - Bessel function

Reserved words

See the man page