bc Command Cheat Sheet
bc (Basic Calculator) is an arbitrary precision calculator language. It parses and executes an interactive execution of statements and is often used for scripting and complex mathematical calculations in the Linux terminal where standard shell arithmetic falls short.
Synopsis
bc [ -hlwsqv ] [long-options] [ file ... ]
Description
bc supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language. A standard math library is available by command line option. If requested, the math library is defined before processing any files.
Basic Usage
Interactive Mode
Type bc to enter the interactive shell. Type expressions and press Enter.
$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
1 + 2
3
scale=2
10 / 3
3.33
quit
Pipe Input
echo "10 + 5" | bc
# Output: 15
Use Standard Math Library
bc -l
Loads functions like sine (s), cosine (c), arctan (a), natural log (l), exponential (e), and Bessel functions (j).
Command Line Options
| Option | Long Option | Description |
|---|---|---|
-h |
--help |
Print usage and exit |
-i |
--interactive |
Force interactive mode |
-l |
--mathlib |
Define standard math library |
-w |
--warn |
Give warnings for extensions to POSIX bc |
-s |
--standard |
Process exactly to POSIX standard |
-q |
--quiet |
Do not print welcome message |
-v |
--version |
Print version number and exit |
Arithmetic Operations
Basics
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
^ Exponentiation
Increment/Decrement
++ Increment (prefix/postfix)
-- Decrement (prefix/postfix)
Example:
i = 1
i++
# i is now 2
Assignment
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
^= Power and assign
Variables and specific
Variables
- Simple variables:
name - Arrays:
name[expression] - Names must start with a letter.
- Variables are initialized to 0.
x = 10
y = 20
total = x * y
total
# Output: 200
Special Variables
| Variable | Description | Default |
|---|---|---|
scale |
Digits after decimal point | 0 |
ibase |
Input number base | 10 |
obase |
Output number base | 10 |
last |
The value of the last printed number | 0 |
Precision and Scaling
Standard shell arithmetic is integer only. bc handles floating point.
Using Scale
# Default scale is 0 (integer division)
echo "10 / 3" | bc
# Output: 3
# Set scale
echo "scale=2; 10 / 3" | bc
# Output: 3.33
echo "scale=10; 10 / 3" | bc
# Output: 3.3333333333
Math Library Scale
When using -l, scale is automatically set to 20.
bc -l
scale
# Output: 20
Base Conversion
bc is excellent for converting between number systems (Hex, Binary, Decimal).
Decimal to Hex
echo "obase=16; 255" | bc
# Output: FF
Hex to Decimal
echo "ibase=16; FF" | bc
# Output: 255
Decimal to Binary
echo "obase=2; 10" | bc
# Output: 1010
Binary to Decimal
echo "ibase=2; 1010" | bc
# Output: 10
Binary to Hex
echo "obase=16; ibase=2; 11110000" | bc
# Output: F0
Note: Always set obase before ibase if you are changing both, because obase is defined in terms of the current ibase.
Logic and Control Structures
bc supports C-like control flow statements.
Relational Operators
(Used in if, while, for)
< Less than
> Greater than
<= Less or equal
>= Greater or equal
== Equal
!= Not equal
Boolean
Return 1 for true, 0 for false.
echo "10 > 5" | bc
# Output: 1
If Statement
if (condition) expression
if (condition) statement else statement
Example:
echo "x=10; if(x > 5) print \"Big\" else print \"Small\"" | bc
# Output: Big
While Loop
while (condition) statement
Example:
echo "i=1; while(i<=5) { print i; i++ }" | bc
For Loop
for (init; condition; update) statement
Example:
echo "for(i=1; i<=5; i++) print i" | bc
Functions
You can define custom functions in bc.
Syntax
define name ( parameters ) {
auto list # Local variables
statement_list
return ( expression )
}
Example Function
Save to functions.bc:
define fact(x) {
if (x <= 1) return (1);
return (fact(x-1) * x);
}
Run:
bc functions.bc
fact(5)
# Output: 120
The Math Library (-l)
Available functions when using bc -l.
| Function | Description |
|---|---|
s(x) |
Sine of x (radians) |
c(x) |
Cosine of x (radians) |
a(x) |
Arctangent of x (returns radians) |
l(x) |
Natural logarithm (ln) of x |
e(x) |
Exponential function (e^x) |
j(n,x) |
Bessel function of order n of x |
Examples
# Calculate Pi (4 * arctan(1))
echo "scale=10; 4*a(1)" | bc -l
# Output: 3.1415926532
# Square Root (sqrt is built-in, doesn't need -l but respects scale)
echo "scale=4; sqrt(2)" | bc
# Output: 1.4142
Input/Output
Print Statement
Calculations print their result automatically. Use print for formatted output.
print "The value is ", x, "\n"
Read
read() reads a number from standard input.
x = read()
Scripting with bc
Here Strings
result=$(bc <<< "scale=2; 100 / 3")
echo $result
Here Documents
bc << EOF
scale = 4
a = 10
b = 3
a / b
EOF
Shell Script Integration
#!/bin/bash
# Calculate disk usage percentage
total=1000
used=450
percent=$(echo "scale=2; ($used / $total) * 100" | bc)
echo "Usage: $percent%"
Advanced Tricks
Comparing Floating Point Numbers
Shells (bash) can't compare floats. Use bc.
val=3.14
threshold=3.0
if (( $(echo "$val > $threshold" | bc -l) )); then
echo "Value is greater"
else
echo "Value is smaller"
fi
Calculating Factorials
echo "define f(x) {if (x<=1) return (1); return (f(x-1)*x)}; f(10)" | bc
Convert Seconds to Hours:Minutes:Seconds
secs=3665
h=$(echo "$secs / 3600" | bc)
m=$(echo "($secs % 3600) / 60" | bc)
s=$(echo "$secs % 60" | bc)
printf "%02d:%02d:%02d\n" $h $m $s
# Output: 01:01:05
Limits and Constraints
bcnumbers can have up toBC_BASE_MAXdigits.scaleis limited by memory.- Variable names are case sensitive.
Common Errors
integer division truncation
echo "5/2" | bc
# Output: 2 (Not 2.5!)
Fix: Set scale.
echo "scale=2; 5/2" | bc
# Output: 2.50
syntax error
Usually missing quotes or incorrect syntax.
# Wrong
echo 1 + 2 | bc
# Right
echo "1 + 2" | bc
Alternatives
- expr: Older, integer only.
- awk: Good for floating point, standard on most systems.
- python: Powerful but slower for simple pipes.
- calc: An advanced command line calculator (often needs install).
- dc: Reverse polish notation calculator (installed with bc).
Tips and Best Practices
- Always Quote Expressions - Prevents shell expansion of
*or(). - Set Scale Early - If you need precision, set
scalefirst statement. - Library Usage - Use
bc -lfor complex math (trig, logs). - Base Conversions - Remember
obasebeforeibasefor sanity. - Use Variables - Makes complex formulas readable.
- Last Result - The
lastvariable holds the previous result. - Quiet Mode - Use
-qin scripts to suppress copyright header (though usually suppressed in pipes). - Script Files - Save complex logic in
.bcfiles for reuse.
Exit Status
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | Error in calculation or syntax |