0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use bc for Calculations in Bash Scripts

Use the bc command in bash to perform calculations by piping expressions to it or using here-strings. For example, echo "5 + 3" | bc outputs 8. This allows bash to handle floating-point and complex math easily.
📐

Syntax

The basic syntax to use bc in bash is to echo a math expression and pipe it to bc. You can also use here-strings for inline calculations.

  • echo "expression" | bc: Sends the expression to bc for calculation.
  • bc <<< "expression": Uses here-string to pass the expression.
  • scale=n: Sets decimal precision for floating-point results inside bc.
bash
echo "5 + 3" | bc
bc <<< "10 / 4"
echo "scale=2; 10 / 4" | bc
Output
8 2 2.50
💻

Example

This example shows how to calculate the sum, division with decimals, and multiplication using bc in bash.

bash
#!/bin/bash

# Sum of two numbers
echo "5 + 7" | bc

# Division with 3 decimal places
echo "scale=3; 10 / 3" | bc

# Multiplication
result=$(bc <<< "12 * 3")
echo "$result"
Output
12 3.333 36
⚠️

Common Pitfalls

Common mistakes when using bc include:

  • Not setting scale for decimal precision, which causes integer division results.
  • Forgetting to quote expressions, leading to shell interpretation errors.
  • Trying to use bash arithmetic $(( )) for floating-point math, which only supports integers.

Correct usage requires quoting expressions and setting scale when decimals are needed.

bash
echo "10 / 4" | bc  # Wrong: no scale, outputs 2

echo "scale=2; 10 / 4" | bc  # Right: outputs 2.50
Output
2 2.50
📊

Quick Reference

CommandDescription
echo "expression" | bcCalculate expression using bc
bc <<< "expression"Calculate expression using here-string
scale=nSet decimal places to n inside bc
echo "scale=2; 5 / 2" | bcDivide with 2 decimal places
result=$(bc <<< "12 * 3")Store calculation result in variable

Key Takeaways

Use bc to perform floating-point and complex math in bash.
Always quote math expressions when passing to bc to avoid shell errors.
Set scale inside bc to control decimal precision.
Use piping or here-strings to send expressions to bc.
Bash arithmetic $(( )) only supports integers, so use bc for decimals.