Use bc for Precise Shell Arithmetic and Small Calculations
Shell arithmetic only does integers, so the moment you need decimals, a base conversion or a repeatable formula, bc is the tool to reach for. This guide covers the installed GNU bc 1.07.1 for decimal arithmetic, controlled precision, base conversion and repeatable calculations from the shell. Allow about ten minutes. Everything here runs as your ordinary user; no elevated privileges are needed.
The route
Jump straight to the step you need, or tick off Done means at the end.
- 1. Confirm the installed implementation
- 2. Run one calculation without entering a session
- 3. Control decimal precision deliberately
- 4. Use the standard maths library when needed
- 5. Convert numbers between bases
- 6. Save a repeatable calculation in a file
- 7. Choose diagnostic and compatibility options
- 8. Check failures before trusting output
1. Confirm the installed implementation
$ 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
- Two things to check first: the executable your shell will run, and its package version.
- Why it matters: GNU
bcis a small language as well as an interactive calculator, and this guide follows the GNU implementation, so an extension such asprintor the maths library may not exist elsewhere.
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
$ printf 'scale=5; 10/3\n' | bc
3.33333
$ printf '10/3\n' | bc
3
- Pipe for a one-off result. A newline terminates the expression, and the result goes to standard output.
- Watch the default scale. It is zero, so division truncates to an integer unless you set
scalefirst, as the second example shows. - Quote carefully. Keep the calculation in single quotes when the shell should pass operators and punctuation unchanged.
- Do not feed it untrusted text.
bcexecutes 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 once standard input reaches end of file.
3. Control decimal precision deliberately
$ 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
scalecontrols digits after the decimal point for operations such as division. Set it at the start of a calculation and make the rounding policy explicit in the surrounding script.- GNU
bctruncates, it does not round. Calculations happen in decimal and division results are truncated. scaleis not a display setting. It affects the calculation, and multiplication can retain the scales of its operands.- For money or measurements, 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
$ 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
-lpreloads the standard maths library and sets the default scale to 20 in this mode.- Trigonometry uses radians, so convert degrees before calling
sorc. - Library contents: sine, cosine, arctangent, natural logarithm, exponential and Bessel functions.
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
$ printf 'ibase=16; FF\n' | bc
255
$ printf 'obase=16; 255\n' | bc
FF
$ printf 'ibase=2; obase=16; 11111111\n' | bc
FF
ibasesets the input base,obasethe output base. Both default to 10.- Range: GNU
bcaccepts bases from 2 through 36, with letters in input numbers written in upper case. - Order matters. Changing
ibasealso changes how later numeric constants are read, so afteribase=16, digits in a later assignment are interpreted as hexadecimal. - Keep base changes near the values they govern, and use separate invocations for unrelated conversions. Limits can vary by installation; ask the local processor with the
limitsstatement if a calculation approaches a boundary.
6. Save a repeatable calculation in a file
$ 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
Files are processed in order, then bc reads standard input; this example defines a function, sets precision and prints a result. 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.
$ rm -- /tmp/circle.bc
Warning
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
$ printf 'print "gnu extension\n"\n' | bc -w
gnu extension
$ printf '1+1\n' | bc -s
2
-qsuppresses the normal GNU welcome in an interactive session.-wwarns about GNU extensions; the first example uses GNU'sprintstatement, and the warning does not make the extension portable.-sprocesses exactly the POSIXbclanguage;POSIXLY_CORRECThas the same effect.- Test with
-swhen portability is a requirement, and avoid relying on multi-letter names,else,readorprintin POSIX-only programs.
8. Check failures before trusting output
$ 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
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. 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
- Implementation confirmed: you know which GNU
bcexecutable and package version you are using. - Scale set explicitly: non-integer calculations account for truncation.
- Maths library used consciously:
-land radians only when needed. - Base changes kept local:
ibaseandobasesit next to the values they affect. - Calculator files reviewed: before running, and only temporary files removed once no longer needed.
- Exit status checked: output verified rather than trusted on sight.