bc - the basic calculator 2022-05-15

Description: How I use and customize the bc CLI calculator

Reading Time: 2

Tags: Unix

bc is the standard Unix CLI calculator. Here are a few tricks I've come across in using it.

It's frequently quicker to start up than most other calculators which might be separate applications or desktop widgets. bc will also let you pipe a set of equations into it, and print the results. Different equations can be separated with a semicolon.

There's also dc, which is reverse polish notation (RPN), which can be useful if you prefer that entry method (and fewer parenthesis).

Defaults

By default bc operates only on integer values, but has an internal scale variable controls the number of digits displayed after the decimal point. It's frequently advantageous to have the scale set to a default value, but bc has no default configuration file. Many versions of bc also support the BC_ENV_ARGS environment var, which supplies default CLI arguments - if set in this way (which could be put in a shell RC file):

export BC_ENV_ARGS="-q $(echo ~)/.bc"

The ~/.bc file can then contain:

scale=5

Which makes the scale value set to 5 in every invocation.

Scripting example

One example of using BC in this way - suppose you needed a random number between two values, such as between 1 and 21 inclusive. If you echo the shell variable $RANDOM into a modulo function (which gives between 0 and a number), and add 1 to make it inclusive:

echo "scale=0; $RANDOM % 21 + 1" | bc

Note that the scale=0 is included to remove the scale value given in the ~/.bc dotfile as given above.

Using bc to calculate within Vim

bc comes in handy when you're editing a text document and need to do math. I use Vim primarily as an editor, and if I type a few math formulas, optionally separated by semicolons:

2^22-1; 33*33

Then select the text in visual mode, hit : to enter ex mode, then type !bc to pipe the selection into bc, the formula will be replaced with the result, one result per line, without leaving the editor:

4194303
1089

Note that Vim doesn't pass your environmental vars through to sub-processes, so the scale value set earlier isn't applied.