The bc (Basic Calculator) command in Linux is an arbitrary-precision calculator language that allows you to perform mathematical operations with a level of precision that standard shell arithmetic cannot handle. While the Bash shell can perform basic integer math using $(( )), it cannot handle floating-point decimals. The bc utility solves this by providing a full environment for floating-point arithmetic, complex mathematical functions, and programmable scripts, making it essential for system administrators and developers who need exact calculations for resource allocation or data processing.
What You'll Need
- A Linux terminal or a Unix-like environment (macOS, BSD).
- Basic familiarity with the command line interface.
- Root or sudo privileges (only if the package is not pre-installed on your distribution).
Step-by-Step
-
Check if bc is installed:
Open your terminal and type
bc -v. If the command is found, it will display the version number. If you see an error stating "command not found," you must install it. On Debian-based systems (like Ubuntu), usesudo apt install bc. On RHEL-based systems (like Fedora or CentOS), usesudo dnf install bc. -
Enter Interactive Mode:
Simply type
bcand press Enter. Your prompt will change, and you will enter thebcenvironment. In this mode, you can type mathematical expressions directly, andbcwill output the result immediately after you press Enter. For example, typing10 + 5will return15. -
Set Decimal Precision (The scale command):
By default,
bcperforms integer division. If you divide 10 by 3, it will return 3. To get decimal results, you must set thescalevariable. Typescale=2to ensure all results are rounded to two decimal places. Now, typing10 / 3will return3.33. You can set the scale to any number, such asscale=10for high-precision scientific calculations. -
Perform Advanced Math with the Math Library:
To access advanced functions like sine, cosine, logarithms, and square roots, you must start
bcwith the-lflag. Typebc -l. This loads the standard math library and automatically sets the default scale to 20. In this mode, you can use functions such ass(x)for sine,c(x)for cosine,l(x)for natural logarithms, ande(x)for exponential functions. -
Use bc in a Non-Interactive Pipe:
For automation and shell scripting, you often want to pass a calculation to
bcwithout entering the interactive shell. You can do this using a pipe (|). For example, runecho "15.5 * 3.2" | bc. The shell sends the string tobc, which processes it and returns49.60to the terminal. -
Utilize Here-Documents for Complex Scripts:
If you have multiple calculations to perform in a script, use a "here-document" to send a block of commands to
bc. This is cleaner than multiple echo statements. Example:bc << EOF scale=4 a = 10.5 b = 2.1 a / b EOFThis will execute the assignments and the division, outputting5.0000. -
Exit the bc Environment:
When working in interactive mode, you can exit by typing
quitand pressing Enter, or by using the keyboard shortcutCtrl+D.
Common Mistakes
The most frequent error users encounter is forgetting to set the scale. Because bc defaults to a scale of 0, many users assume the tool is broken when 5/2 returns 2 instead of 2.5. Always remember that scale defines the number of digits after the decimal point for the result of a division.
Another common mistake is attempting to use standard C-style math functions (like sin() or log()) without the -l flag. If you try to use s(1) in the default mode, bc will return an error or simply not recognize the function. The math library is a separate module that must be explicitly loaded at startup.
Users also frequently confuse the bc syntax with Bash syntax. In Bash, you might use expr or (( )), but bc is its own language. For instance, you cannot use Bash variables directly inside the bc interactive prompt; you must pass them in via a pipe or a string using the echo command.
Tips
To make your scripts more readable, use variables within bc. Instead of one long string of numbers, assign values to letters (e.g., x = 50; y = 20; x / y). This makes debugging much easier when you are calculating complex formulas.
If you are dealing with very large numbers, bc is the ideal tool because it is not limited by the 64-bit integer limit of the CPU. You can calculate factorials or powers of massive numbers that would cause a "buffer overflow" or "integer overflow" in other languages.
Combine bc with the printf command in Bash to format the output. Since bc does not provide a way to add leading zeros (e.g., it returns .5 instead of 0.5), piping the result to printf "%.2f\n" can make the output more professional and human-readable.
Troubleshooting
If you get a "Command not found" error: This means the bc package is not installed. Use your distribution's package manager (apt, dnf, or pacman) to install it. Ensure you are using sudo, as installing software requires administrative privileges.
If the output is an integer when you expected a decimal: Check your scale setting. If you are using a pipe, ensure scale=X is included in the string sent to bc. For example: echo "scale=2; 10/3" | bc. If you are in interactive mode, type scale=2 and press Enter before performing the division.
If the math library functions (s, c, l, e) aren't working: Verify that you started the program with bc -l. If you are already inside the interactive prompt, you cannot load the library; you must exit and restart the command with the -l flag.
If you see unexpected results with very large numbers: Ensure you aren't accidentally using a shell variable that is being truncated by the shell before it even reaches bc. Pass the variables inside quotes to ensure the shell treats them as strings until bc parses them.
Frequently Asked Questions
How do I calculate a square root in bc?
You can use the sqrt() function. For example, echo "sqrt(16)" | bc will return 4. Remember to set the scale if the root is not a whole number.
Can bc handle negative numbers?
Yes, bc fully supports negative numbers. You can perform operations like -10 + 5 or -5 * -2, and it will follow standard algebraic rules for signs.
Is bc faster than Python for math?
For simple calculations and shell integration, bc is faster to launch and requires less overhead than starting a Python interpreter. However, for complex data analysis or massive loops, Python's optimized libraries are more efficient.
How do I perform exponentiation in bc?
Use the ^ operator. For example, echo "2^10" | bc will return 1024. This is useful for calculating binary powers or growth rates in scripts.
Does bc support hexadecimal or binary?
Yes, bc can work in different bases. Use ibase for the input base and obase for the output base. To convert a decimal number to hex, you would set obase=16 before entering the number.
Can I save bc calculations to a file?
Yes, you can redirect the output using the standard Linux redirection operator. For example, echo "10 + 10" | bc > result.txt will save the answer 20 into a file named result.txt.