You can use bc for calculations in the terminal by echoing expressions and piping them to bc. Here’s a step-by-step guide:
-
Basic Usage:
You can perform simple calculations directly in the terminal. For example:echo "5 + 3" | bcThis will output
8. -
Using Variables:
You can also use variables in your calculations:a=10 b=4 result=$(echo "$a * $b" | bc) echo "Result: $result" -
Floating-Point Calculations:
To perform floating-point arithmetic, you can set the scale for decimal precision:echo "scale=2; 10 / 3" | bcThis will output
3.33. -
Multiple Operations:
You can perform multiple operations in a single command:echo "scale=2; (10 + 5) * (3 - 1)" | bcThis will output
30.00. -
Interactive Mode:
You can startbcin interactive mode by simply typingbcin the terminal. You can then enter expressions directly:$ bc 10 + 5 15 -
Using
scalefor Precision:
When performing division, you can specify the number of decimal places usingscale:echo "scale=3; 10 / 3" | bcThis will output
3.333.
By using bc, you can handle a wide range of arithmetic operations, including both integer and floating-point calculations.
