This post was originally published on go2linux.org on February 22, 2009. The domain is no longer mine, but I am the original author. I am republishing it here on garron.me with corrections and improvements.
Introduction
bc is a precision arithmetic calculator available on almost every Linux and Unix system. You can use it for quick command-line calculations, inside shell scripts (where bash has no native floating-point support), or interactively to define and call your own functions.
Using bc from the command line
Pass an expression with echo and pipe it to bc:
echo "2+2" | bc
Output:
4
By default bc shows no decimal places. For division, use scale to set the number of decimal places:
echo "scale=3; 5/3" | bc
Output:
1.666
Or load the built-in math library with -l, which sets scale to 20 automatically:
echo "5/3" | bc -l
Output:
1.66666666666666666666
Math functions available with -l
The -l flag loads the standard math library:
| Function | Description |
|---|---|
| s(x) | sine of x (radians) |
| c(x) | cosine of x (radians) |
| a(x) | arctangent of x |
| e(x) | e raised to the power of x |
| l(x) | natural logarithm of x |
| sqrt(x) | square root of x |
Computing the square root of 2:
echo "sqrt(2)" | bc -l
Output:
1.41421356237309504880
Interactive mode
Run bc -l without piping to enter the interactive shell:
bc -l
Type expressions directly:
2^10
1024
scale=5
22/7
3.14285
Press Ctrl+D to exit.
Defining custom functions
In interactive mode you can define functions:
define carea() {
print "Circle radius? "; r = read()
pi = 4*a(1)
a = pi * r^2
return(a)
}
Call it:
carea()
Circle radius? 34
3631.68110754980098363664
Using bc in shell scripts
Bash has no native floating-point arithmetic, so bc is the standard solution:
#!/bin/bash
result=$(echo "scale=2; 100/3" | bc)
echo "100 divided by 3 is: $result"