Session and utilities

The bc command

Arbitrary-precision calculator: decimals and huge numbers from the terminal.

Syntax

echo 'expresión' | bcTry it in the terminal →

Most useful options

-l, --mathlibLoads the math library (s, c, a, l, e, j) and sets scale to 20 by default
-s, --standardAccepts only the POSIX bc language, without the GNU extensions
-w, --warnWarns about every extension that is not part of POSIX bc
-q, --quietDoes not print the GNU bc welcome message

Copy-ready examples

$ echo '2+2' | bcsimple addition.

Example output

4
$ echo '2^10' | bcpower: 2 to the 10th.

Example output

1024
$ echo '1/3' | bcwithout scale, the division is truncated to an integer.

Example output

0
$ echo 'scale=4; 1/3' | bcfour decimals. The semicolon separates the statements.
$ echo 'scale=10; 4*a(1)' | bc -lpi with ten decimals, using the math library.

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
File nonexist is unavailable.bc cannot find the file you pass as an argument.Check the name with ls, or pass the expression through a pipe with echo.
(standard_in) 1: illegal character: $The expression contains a character bc does not recognise. If you type it without quotes, the shell may change it before it reaches bc.Remove the character or write the expression between single quotes.

Typical mistakes

  • Without scale or -l, bc works with integers: 1/3 gives 0 because divisions and multiplications are truncated, not rounded.
  • With -l the default scale becomes 20, but a scale= inside the expression replaces it for that same input.
  • Dividing by zero raises a runtime error and bc returns no result for that expression.

Differences from similar commands

  • expr: does integer arithmetic in the shell: expr 1 / 3 gives 0. bc computes decimals at the precision you set with scale.
  • awk: computes in double-precision floating point, so the number of decimals is fixed. bc lets you choose it.

Related commands

FAQ

How do I get many decimals?

With scale: echo 'scale=4; 1/3' | bc. The higher scale is, the more digits after the point.

Can I use variables and loops?

Yes. bc is a language with variables, for, while and define for functions. A program goes in a file you pass as an argument: bc program.bc.

What are ibase and obase?

They are the input and output bases. With obase=2 results come out in binary: echo 'obase=2; 10' | bc prints 1010.

How do I put the result in a variable?

With command substitution: total=$(echo '2^10' | bc). The shell strips the trailing newlines from the result.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course