The bc command is a command-line calculator that reads expressions from standard input or files and outputs the results. You enter arithmetic expressions, variable assignments, or function calls, and bc prints the computed answer. This article shows you how to use bc with practical examples, covering basic arithmetic, variables, functions, and scripting.
What is bc?
bc (basic calculator) is a Unix utility that has been around since the 1970s. It is a POSIX-standard tool that supports arbitrary precision arithmetic, meaning you can calculate with as many decimal places as you need, limited only by your system’s memory. It is often used in shell scripts for calculations, and it can also be used interactively.
The language is similar to C, with support for variables, arrays, functions, loops, and conditionals. This makes it far more powerful than a simple expr or echo $((...)) for complex calculations.
Basic Usage and Examples
The simplest way to use bc is to pipe an expression to it:
echo '2 + 3' | bcoutputs5echo '10 / 3' | bcoutputs3(integer division by default)echo '10 / 3' | bc -loutputs3.33333333333333333333(with the math library)echo 'scale=2; 10 / 3' | bcoutputs3.33(set decimal places)
You can also run bc interactively by typing bc and then entering expressions. To exit, type quit or press Ctrl-D.
Setting the Scale (Decimal Places)
By default, bc gives integer results for division. The scale variable controls the number of digits after the decimal point. For example:
echo 'scale=4; 22 / 7' | bcoutputs3.1428echo 'scale=10; 1 / 3' | bcoutputs.3333333333
Note that scale only affects division, multiplication, and the square root function. Addition and subtraction always use the maximum scale of the operands.
Using the Math Library (-l)
The -l option loads the standard math library, which provides functions like sine, cosine, arctangent, natural logarithm, and exponential. It also sets scale to 20 by default. Examples:
echo 's(0)' | bc -loutputs0(sine of 0 radians)echo 'c(0)' | bc -loutputs1(cosine of 0)echo 'l(2)' | bc -loutputs.69314718055994530941(natural log of 2)echo 'e(1)' | bc -loutputs2.71828182845904523536(e to the power 1)echo 'sqrt(2)' | bc -loutputs1.41421356237309504880
Variables and Expressions
You can assign values to variables and use them in expressions. This is useful for repeated calculations:
echo 'x = 5; y = 3; x * y + 1' | bc
Outputs 16. You can also use the -e option (in newer versions) to pass expressions directly:
bc -e 'x = 5; y = 3; x * y + 1'
Functions and Control Structures
bc supports user-defined functions and control flow. Here is a simple function to calculate the factorial of a number:
define fact(n) {
if (n <= 1) return (1);
return (n * fact(n - 1));
}
fact(5)
Save this to a file, say fact.bc, and run bc fact.bc. The output will be 120. You can also use loops:
for (i = 1; i <= 10; i++) i^2
This prints the squares of 1 through 10, each on a new line.
Using bc in Shell Scripts
bc is often used in shell scripts for floating-point arithmetic. For example, to calculate the average of three numbers:
#!/bin/bash a=10; b=20; c=30 echo "scale=2; ($a + $b + $c) / 3" | bc
Outputs 20.00. You can also capture the result in a variable:
result=$(echo "scale=2; 10 / 3" | bc) echo "The result is $result"
Common Pitfalls and Tips
- Integer division: Without
scale,bctruncates. Always setscaleif you need decimals. - Input bases: You can change the input and output base with
ibaseandobase. For example,echo 'obase=2; 10' | bcoutputs1010(binary). - Precision: For very high precision, set
scaleto a large number. However, this can be slow for huge scales. - Negative numbers: In some versions,
-lchanges the behavior of negative numbers. Test your expressions. - Quoting: When using
echowithbc, always quote the expression to avoid shell interpretation of special characters like*or^.
Frequently Asked Questions
How do I calculate the square root in bc?
Use the sqrt() function. It is available by default, but with -l it gives more decimal places. Example: echo 'sqrt(16)' | bc outputs 4.
How do I use bc for hexadecimal or binary conversions?
Set ibase and obase. For example, to convert decimal 255 to hex: echo 'obase=16; 255' | bc outputs FF. To convert hex to decimal: echo 'ibase=16; FF' | bc outputs 255.
Can bc handle very large numbers?
Yes, bc handles arbitrary precision integers and decimals. You can calculate numbers with thousands of digits, limited only by memory and time.
What is the difference between bc and expr?
expr is a basic tool for integer arithmetic and string operations, while bc supports floating-point, functions, and complex expressions. For any non-trivial calculation, bc is the better choice.
How do I pass a command-line argument to bc?
You can use the -e option (if supported) or pipe a string that includes the variable. For example: echo "scale=2; $1 / 3" | bc in a script.
Why does bc give me a different result than a calculator?
Check the scale. Many calculators default to a fixed number of decimals, while bc defaults to integer division. Set scale to match your needs.
Related
Formula used
in t | Finish time | min | 50 | 0 in d | Distance | km | 10 | 0 | 100000 out pace | Average pace | min/km | t / d | 2 out speed | Average speed | km/h | d / (t / 60) | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Turn Off Backup Encryption in iTunes?
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It