Home / Alt manpages / bc(1)

  • bc(1)
  • User command
  • linux

Use bc for Precise Shell Arithmetic and Small Calculations

You will use the installed GNU bc 1.07.1 for decimal arithmetic, controlled precision, base conversion and repeatable calculations from the shell. Allow about ten minutes for the examples. Everything here runs as your ordinary user; no elevated privileges are needed.

1. Confirm the installed implementation

GNU bc is a small language as well as an interactive calculator. This guide follows the GNU implementation installed by the bc package on this machine. Check both the executable selected by your shell and its package version before relying on an extension such as print or the maths library.

$ command -v bc
/usr/bin/bc
$ dpkg-query -W -f='${Package} ${Version}\n' bc
bc 1.07.1-3ubuntu4
$ bc --version | head -n 1
bc 1.07.1

Checkpoint: the first path should be the command you intend to run, and the version should match the examples. If a different implementation is selected, read its own manual before copying GNU-specific code.

2. Run one calculation without entering a session

For a one-off result, pipe an expression into bc. A newline terminates the expression, and the result is written to standard output. The default scale is zero, so division is truncated to an integer unless you set it first.

$ printf 'scale=5; 10/3\n' | bc
3.33333
$ printf '10/3\n' | bc
3

Keep the calculation in single quotes when the shell should pass operators and punctuation unchanged. Do not put untrusted text into an expression: bc executes a language, not a restricted number parser. For values supplied by another program, validate that they contain only the numeric form and operations you intend.

There is no persistent state change in these commands. The process exits after standard input reaches end of file.

3. Control decimal precision deliberately

scale controls digits after the decimal point for operations such as division. GNU bc calculates in decimal and truncates division results rather than rounding them. Set the scale at the start of a calculation and make the expected rounding policy explicit in the surrounding script.

$ printf 'scale=2; 1/8\n' | bc
.12
$ printf 'scale=2; 10/3\n' | bc
3.33
$ printf 'scale=2; (10/3)*100\n' | bc
333.00

The value of scale is not a general display setting. It affects the calculation, and multiplication can retain the scales of its operands. If money or measurements need rounding rather than truncation, calculate an extra digit and apply a checked rounding rule in a language or tool that provides the policy you need. Do not silently present a truncated value as rounded.

4. Use the standard maths library when needed

Pass -l to preload the standard maths library. GNU bc sets the default scale to 20 in this mode. The functions use radians for trigonometry, so convert degrees before calling s or c. The library includes sine, cosine, arctangent, natural logarithm, exponential and Bessel functions.

$ printf 'scale=5; 4*a(1)\n' | bc -l
3.14159
$ printf 'scale=5; s(1)\n' | bc -l
.84147
$ printf 'scale=5; 90*a(1)/180\n' | bc -l
1.57079

Checkpoint: verify the scale in the input rather than relying on the -l default. A pipeline that needs five decimal places should say scale=5 even when it also uses -l.

5. Convert numbers between bases

Use ibase for the input base and obase for the output base. Both default to base 10. GNU bc accepts bases from 2 through 36, with letters in input numbers written in upper case. Assign the input base before reading the number.

$ printf 'ibase=16; FF\n' | bc
255
$ printf 'obase=16; 255\n' | bc
FF
$ printf 'ibase=2; obase=16; 11111111\n' | bc
FF

Changing ibase also changes how later numeric constants are read. That makes assignments easy to misread: after ibase=16, the digits in a later assignment are interpreted as hexadecimal. Keep base changes near the values they govern, and use separate invocations for unrelated conversions. The maximum base and other limits can vary by installation; ask the local processor with the limits statement if a calculation approaches a boundary.

6. Save a repeatable calculation in a file

For a calculation used more than once, put the bc program in a file and pass that file on the command line. Files are processed in order, then bc reads standard input. This example defines a function, sets precision and prints a result.

$ cat > /tmp/circle.bc <<'EOF'
scale=5
define circumference(r) {
  return (2 * a(1) * r)
}
print circumference(2), "\n"
EOF
$ bc -l /tmp/circle.bc
12.56636

The here-document creates a temporary file under /tmp, not a system configuration file. Replace the example path with a private working directory for a calculation you need to keep. Remove the temporary file when it is no longer needed:

$ rm -- /tmp/circle.bc

That removal is irreversible. If the file contains a useful calculation, copy it to a reviewed project location first. Do not run a calculator file obtained from an untrusted source without reading it: bc supports assignments, loops, functions, file input through read and commands such as quit.

7. Choose diagnostic and compatibility options

Use -q to suppress the normal GNU welcome in an interactive session, -w to warn about GNU extensions, and -s to process exactly the POSIX bc language. POSIXLY_CORRECT has the same effect as -s. These options help when a script must work beyond this installed GNU implementation.

$ printf 'print "gnu extension\n"\n' | bc -w
gnu extension
$ printf '1+1\n' | bc -s
2

The first example uses GNU's print statement. With -w, warnings are shown for extensions when applicable; the option does not make those extensions portable. Test with -s when portability is a requirement, and avoid relying on multi-letter names, else, read or print in POSIX-only programs.

8. Check failures before trusting output

A successful-looking output is not enough if the input file or scale was wrong. Check the exit status and keep standard error visible. A missing command-line file is a fatal error in this implementation.

$ printf 'scale=3; 10/3\n' | bc >/tmp/bc-result
$ status=$?
$ test "$status" -eq 0 && cat /tmp/bc-result
3.333
$ rm -- /tmp/bc-result

If a result is empty or unexpectedly truncated, inspect the expression for an omitted scale, an earlier ibase assignment or shell quoting that changed the input. If bc reports a syntax or runtime error, fix the input rather than adding sudo; elevated privileges do not repair calculator code. In a non-interactive run, an interrupt terminates the process, so rerun the calculation after correcting the input.

Done means

  • You confirmed which GNU bc executable and package version you are using.
  • Your non-integer calculations set scale explicitly and account for truncation.
  • You used -l and radians consciously when calling the maths library.
  • You placed ibase and obase next to the values they affect.
  • You reviewed calculator files before running them and removed only temporary files you no longer need.
  • You checked the exit status and output instead of treating any printed number as automatically correct.