How to Use bc Command for Linux Inline Math

The Linux operating system primarily relies on the bc (Basic Calculator) utility to perform inline mathematical calculations, especially when dealing with floating-point numbers that native shell environments like Bash cannot compute. This article explains how Linux executes inline math using bc, detailing standard input piping, command substitution, decimal precision control, and direct command-line execution methods for shell scripting and automation.

Understanding bc in Linux

The standard Linux shell (Bash) supports only integer arithmetic natively via syntax such as $((5 + 2)). When decimal points, high-precision operations, or advanced functions are required, Linux defers calculations to external tools. The bc command is a standard POSIX-compliant language processor that accepts mathematical statements from standard input, calculates the results with arbitrary precision, and writes them to standard output.

Using Pipes for Inline Arithmetic

The most common method to perform an inline calculation is piping an expression directly into bc via the echo or printf command.

echo "15 + 27" | bc
echo "12.5 * 4.2" | bc

Linux processes the text string inside echo, passes the string to standard input via the pipe (|), and bc returns the evaluated result directly to the terminal.

Controlling Precision with scale

By default, division in bc produces an integer truncated toward zero. To preserve decimal places, you must set the scale internal variable, which defines the number of digits after the decimal point.

echo "scale=2; 10 / 3" | bc

This returns 3.33. Multiple expressions are separated by a semicolon, allowing configuration commands to execute sequentially before the mathematical expression is evaluated.

Alternatively, using the -l (math library) flag automatically sets scale to 20 and enables standard functions:

echo "10 / 3" | bc -l

Storing Inline Results in Variables

To use the calculated output within shell scripts or command chains, Linux utilizes command substitution ($(...)):

result=$(echo "scale=4; 355 / 113" | bc)
echo "The calculated value is: $result"

The shell spawns a subshell, pipes the calculation through bc, captures the standard output, and assigns it to the target variable.

Using Here-Strings

Modern shells like Bash support "here-strings" (<<<), which eliminate the need for a separate echo command and an extra subshell pipe, providing a cleaner inline syntax:

bc <<< "scale=3; 100 / 7"

Variable assignment using a here-string:

area=$(bc <<< "scale=2; 3.14159 * 5 * 5")

Advanced Operations and Functions

With the -l flag, bc handles roots, exponents, logarithms, and trigonometry natively inline:

By feeding string expressions directly to standard input, Linux systems efficiently execute complex inline arithmetic in one-line terminal commands and automated scripts without writing dedicated program files.