Bash handles arithmetic operations differently than most programming languages. Since bash cannot natively handle floating point numbers, alternate methods must be used for math operations. In this comprehensive guide, we will explore the various techniques for performing arithmetic in bash scripts.
The expr Command
The expr command is one of the oldest ways to evaluate math expressions in bash. For example:
expr 2 + 2
This will output 2 + 2 literally instead of 4. That‘s because expr treats everything as a string by default. To evaluate properly, spaces must be used between operands:
expr 2 + 2
Now it outputs 4 as expected.
Some key points about expr:
- Spaces are required between operators and numbers
- Only integers are supported, no floats
- Operations happen left to right without regard for order of operations
- Useful for simple arithmetic but has limitations
The let Command
The let command is more flexible than expr and doesn‘t require whitespace:
let result=5+5
echo $result # 10
let allows:
- Floating point and integer math
- Variables
- Spaces optional for math operators
- Order of operations respected
One downside is that let can‘t print the result directly. It must be assigned to a variable.
Overall, let fixes several of the limitations of expr.
Double Parentheses
Double parentheses (( )) provide similar arithmetic evaluation as let but with less typing:
((result = 5 + 5))
echo $result # 10
Some notable features:
- Floating point and integer math
- Order of operations respected
- Spaces optional
- Can increment variables directly:
((var++))
For most use cases, double parentheses provide the best combination of brevity and capability for math operations in bash.
The bc Calculator
For precision math and floating point numbers, bc is the go-to choice:
echo "scale=4; 5 / 3" | bc # 1.6667
Features of bc:
- Arbitrary precision floating point numbers
- Math functions like sine, cosine, etc.
- Programmable with loops and conditionals
scalecontrols number of decimal places- Excellent for accurate high precision calculations
The only downside to bc is it has more verbose syntax compared to other options. Overall one of the most robust arithmetic tools in bash.
printf Formatting
While not strictly arithmetic, printf can be used to accurately format numbers:
printf "Pi to 3 places = %.3f\n" 3.14159 # Pi to 3 places = 3.142
When doing floating point math in bash, printf can output the numbers with consistent decimal points.
In Conclusion
Bash provides several capable options for doing math – from simple to advanced operations. For most tasks:
expr– simple integer operationsletor(( ))– convenient integer/float mathbc– precise floating point and advanced functionsprintf– format numbers nicely
Understanding these options will allow effective math directly in bash scripts.


