Web Analytics

Arithmetic Operations

Beginner ~20 min read

Bash provides several ways to perform arithmetic operations in your scripts. From simple addition to complex calculations, understanding these methods is essential for writing practical shell scripts. In this lesson, you'll learn about arithmetic expansion $(( )), the let command, the legacy expr command, and using bc for floating-point math.

Arithmetic Expansion: $(( ))

The most common and recommended way to perform arithmetic in Bash is using arithmetic expansion with $(( )). This syntax evaluates the expression and returns the result.

Output
Click Run to execute your code
Operator Description Example Result
+ Addition $((5 + 3)) 8
- Subtraction $((5 - 3)) 2
* Multiplication $((5 * 3)) 15
/ Division (integer) $((10 / 3)) 3
% Modulus (remainder) $((10 % 3)) 1
** Exponentiation $((2 ** 3)) 8
Key Point: Inside $(( )), you don't need the $ prefix for variables. Both $((a + b)) and $(($a + $b)) work, but the first is cleaner and preferred.

The let Command

The let command is another way to perform arithmetic. It evaluates expressions and assigns the result to variables. It's particularly useful for increment/decrement operations.

Output
Click Run to execute your code
Pro Tip: Use (( )) (without the $) as a shorthand for let. For example, ((count++)) is equivalent to let count++. The (( )) form is often preferred for conditions and loops!

The expr Command (Legacy)

The expr command is an older, POSIX-compliant method for arithmetic. While still functional, it's considered legacy. You'll encounter it in older scripts, so it's good to understand it.

Output
Click Run to execute your code
Caution: When using expr:
  • Spaces are required around operators: expr 5 + 3 (not expr 5+3)
  • Multiplication needs escaping: expr 5 \* 3 (the * is a glob character)
  • Modern scripts should prefer $(( )) instead

Floating-Point Arithmetic with bc

Bash only supports integer arithmetic natively. For floating-point (decimal) calculations, use the bc (basic calculator) command. It's a powerful tool for precision math!

Output
Click Run to execute your code
Understanding bc:
  • scale=N sets the number of decimal places
  • Pipe the expression to bc: echo "expression" | bc
  • bc supports functions like sqrt(), s() (sine), c() (cosine)
  • For math functions, use bc -l (load math library)

Assignment Operators

Bash supports compound assignment operators for modifying variables in place. These combine an arithmetic operation with assignment.

# Compound assignment operators
x=10

((x += 5))   # x = x + 5  -> x is now 15
((x -= 3))   # x = x - 3  -> x is now 12
((x *= 2))   # x = x * 2  -> x is now 24
((x /= 4))   # x = x / 4  -> x is now 6
((x %= 4))   # x = x % 4  -> x is now 2
((x **= 3))  # x = x ** 3 -> x is now 8

# Increment and decrement
((x++))      # Post-increment: use then add 1
((++x))      # Pre-increment: add 1 then use
((x--))      # Post-decrement: use then subtract 1
((--x))      # Pre-decrement: subtract 1 then use
Pro Tip: The difference between ((x++)) and ((++x)) matters when used in expressions. Pre-increment changes the value before it's used; post-increment changes it after.

Common Mistakes

1. Spaces in assignments

# Wrong - spaces cause errors
x = 10         # Error: command not found
x= 10          # Error: command not found

# Correct - no spaces around =
x=10
result=$((5 + 3))

2. Expecting floating-point results

# Wrong - Bash integer division truncates
result=$((10 / 3))
echo $result  # Output: 3 (not 3.333)

# Correct - use bc for decimals
result=$(echo "scale=2; 10 / 3" | bc)
echo $result  # Output: 3.33

3. Forgetting to escape * in expr

# Wrong - * expands to filenames
result=$(expr 5 * 3)  # Error or unexpected results

# Correct - escape the asterisk
result=$(expr 5 \* 3)  # Output: 15

# Better - use $(( )) instead
result=$((5 * 3))  # Output: 15

4. Using $ inside (( )) when not needed

# Works but verbose
a=5; b=3
result=$(($a + $b))

# Cleaner - $ is optional inside (( ))
result=$((a + b))

Exercise: Build a Calculator

Task: Create a simple calculator script that demonstrates various arithmetic operations!

Requirements:

  • Define two numbers as variables
  • Perform all 6 basic operations (+, -, *, /, %, **)
  • Use compound operators (++, +=)
  • Calculate a floating-point result using bc
Show Solution
#!/bin/bash
# Simple Calculator

# Define numbers
num1=15
num2=4
echo "=== Simple Calculator ==="
echo "Numbers: num1=$num1, num2=$num2"
echo ""

# Basic operations
echo "--- Basic Operations ---"
echo "Addition: $num1 + $num2 = $((num1 + num2))"
echo "Subtraction: $num1 - $num2 = $((num1 - num2))"
echo "Multiplication: $num1 * $num2 = $((num1 * num2))"
echo "Division: $num1 / $num2 = $((num1 / num2))"
echo "Modulus: $num1 % $num2 = $((num1 % num2))"
echo "Power: $num1 ** 2 = $((num1 ** 2))"
echo ""

# Compound operators
echo "--- Compound Operators ---"
counter=0
echo "Starting counter=$counter"
((counter++))
echo "After counter++: $counter"
((counter+=10))
echo "After counter+=10: $counter"
echo ""

# Floating-point with bc
echo "--- Floating-Point (bc) ---"
float_result=$(echo "scale=4; $num1 / $num2" | bc)
echo "Precise division: $num1 / $num2 = $float_result"

Summary

  • Arithmetic Expansion: $(( )) is the modern, preferred method for integer math
  • let Command: let x=5+3 for arithmetic assignments and increments
  • (( )) Syntax: Same as let but cleaner: ((x++))
  • expr Command: Legacy method, requires spaces and escaping
  • bc Calculator: Use for floating-point: echo "scale=2; 10/3" | bc
  • Operators: +, -, *, /, %, ** for basic math
  • Compound Operators: +=, -=, *=, /=, %=, ++, -- for in-place modification

What's Next?

Now that you can perform calculations, let's learn about Comparison Operators. You'll discover how to compare numbers and strings, which is essential for conditional statements and decision-making in your scripts!