How to Perform Precision Math Using the bc Command in Linux

The standard Linux bash shell is notoriously bad at complex mathematics. While you can force it to perform basic arithmetic (like addition or subtraction), it only understands whole integers. If you ask a standard bash script to divide 10 by 3, it will stubbornly output “3” and completely discard the decimal remainder. To perform high-level, mathematically precise floating-point calculations directly inside your terminal, you must use the bc (Basic Calculator) command.

How the bc Command Works

The bc command is an arbitrary-precision calculator language. Unlike simple arithmetic tools, it can calculate numbers to thousands of decimal places without losing a single bit of mathematical integrity.

To launch the calculator interactively, simply type the command into your terminal and press Enter:

bc

Your prompt will change. You are now inside the calculator engine. You can type complex mathematical equations (e.g., 10 + 5 * 2) and press Enter. The engine respects standard mathematical order of operations, so it will correctly multiply 5 by 2 first, add 10, and output 20.

When you are finished calculating, type quit to exit the engine and return to your standard bash prompt.

How to Calculate Decimal Points (Scale)

Even inside the bc engine, decimal division is restricted by default to keep the output clean. If you type 10 / 3, it will still output 3. To unlock the engine’s true power, you must define the “scale” variable, which dictates exactly how many decimal places the calculator should generate.

Inside the bc prompt, type:

scale=4

Now, if you type 10 / 3, the engine will aggressively calculate the floating-point math and perfectly output 3.3333.

Using bc Inside Bash Scripts

While the interactive mode is great for quick math, the true power of bc lies in its ability to be piped inside automated bash scripts.

If you have a script monitoring disk usage, and you need to mathematically calculate a precise percentage, you can use the echo command to inject the math directly into the bc engine without ever opening the interactive prompt.

echo "scale=2; 55 / 120 * 100" | bc

This command perfectly passes the instructions into the engine. The calculator sets the decimal precision to two places, processes the math, and silently outputs the final percentage back to your bash script, allowing you to trigger alerts based on highly precise, floating-point data.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.