LinuxCommandLibrary

bc

Perform arbitrary-precision arithmetic calculations

TLDR

Start an interactive session

$ bc
copy

Start an interactive session with the standard math library enabled
$ bc [[-i|--interactive]] [[-l|--mathlib]]
copy

Calculate an expression
$ echo '[5 / 3]' | bc
copy

Execute a script
$ bc [path/to/script.bc]
copy

Calculate an expression with the specified scale
$ echo 'scale = [10]; [5 / 3]' | bc
copy

Calculate a sine/cosine/arctangent/natural logarithm/exponential function using mathlib
$ echo '[s|c|a|l|e]([1])' | bc [[-l|--mathlib]]
copy

Execute an inline factorial script
$ echo "define factorial(n) { if (n <= 1) return 1; return n*factorial(n-1); }; factorial([10])" | bc
copy

SYNOPSIS

bc [-h | -i | -l | -q | -s | -v | -V | -w] [p digits] [file ...]

PARAMETERS

-h, --help
    Display help message and exit

-i, --interactive
    Force interactive mode, even with files

-l, --mathlib
    Load math library (defines pi, cos, sin, etc.)

-w, --warn
    Warn on POSIX-incompatible extensions

-q, --quiet
    Suppress version banner on startup

-s, --standard
    Strict POSIX bc mode (disable extensions)

-v, --version
    Print version information and exit

-V
    Alias for --version

-p digits
    Set default output precision

DESCRIPTION

bc is a command-line interpreter for the basic calculator language, supporting arbitrary-precision arithmetic. It processes mathematical expressions interactively or from files, featuring a syntax reminiscent of C. Users can define variables, execute statements, and call functions.

A key strength is handling numbers with unlimited digits, ideal for precise calculations beyond standard integer limits. The -l option loads a math library with functions like sin, cos, log, using radians. Input ends with quit or EOF (Ctrl-D).

bc excels in scripting via pipes, e.g., echo 'scale=10; 1/3' | bc outputs 0.3333333333. The scale variable controls decimal places. It supports loops, conditionals, and custom procedures, making it a lightweight programming tool for math tasks. POSIX-compliant mode ensures portability.

CAVEATS

No floating-point support (fixed-point decimals only); vulnerable to long input causing high memory use; ignores signals in some modes; limited string handling.

SCALE VARIABLE

Controls decimal digits in division; set via scale=N statement, e.g., scale=5; 1/7 yields 0.14285.

LAST VALUE

Results stored in last register for reuse, e.g., 3 * last.

HISTORY

Originated in Unix Version 6 AT&T Bell Labs (1975) by Lorinda Cherry; enhanced in V7 (1979). GNU bc developed by Philip Homburg (1991), now maintained with arbitrary-precision via GMP library.

SEE ALSO

dc(1), expr(1), awk(1)

Copied to clipboard