How to Use Arithmetic in Bash: Simple Guide with Examples
In bash, you can perform arithmetic using the
$(( expression )) syntax or the let command. These allow you to add, subtract, multiply, divide, and use other math operations directly in your scripts.Syntax
Bash supports arithmetic using the $(( expression )) syntax, where expression is the math operation you want to perform. You can also use the let command for arithmetic evaluation.
$(( expression )): Evaluates the expression and returns the result.let expression: Evaluates the expression and assigns the result to variables if used.
bash
result=$(( 5 + 3 )) let result=5+3
Example
This example shows how to add, subtract, multiply, and divide two numbers using $(( )) syntax and print the results.
bash
#!/bin/bash num1=10 num2=4 sum=$(( num1 + num2 )) diff=$(( num1 - num2 )) prod=$(( num1 * num2 )) div=$(( num1 / num2 )) echo "Sum: $sum" echo "Difference: $diff" echo "Product: $prod" echo "Division: $div"
Output
Sum: 14
Difference: 6
Product: 40
Division: 2
Common Pitfalls
Common mistakes include:
- Using single brackets
[ ]instead of$(( ))for arithmetic, which treats values as strings. - Forgetting spaces around operators inside
$(( ))is allowed but can cause confusion. - Using floating-point numbers, which bash arithmetic does not support natively.
Here is a wrong and right way example:
bash
# Wrong way (string concatenation): echo $[ 5 + 3 ] # Deprecated but works # Right way: echo $(( 5 + 3 ))
Output
8
Quick Reference
| Operation | Syntax Example | Description |
|---|---|---|
| Addition | $(( a + b )) | Adds a and b |
| Subtraction | $(( a - b )) | Subtracts b from a |
| Multiplication | $(( a * b )) | Multiplies a by b |
| Division | $(( a / b )) | Divides a by b (integer division) |
| Modulus | $(( a % b )) | Remainder of a divided by b |
| Increment | let a++ | Increases a by 1 |
| Decrement | let a-- | Decreases a by 1 |
Key Takeaways
Use $(( expression )) for clean and easy arithmetic in bash.
Bash arithmetic only supports integers, no floating-point math.
Avoid using single brackets [ ] for math; they are for tests.
The let command is an alternative but less common than $(( )).
Remember division in bash truncates decimals (integer division).