Bash Script to Subtract Two Numbers Easily
Use arithmetic expansion in Bash like
result=$((num1 - num2)) to subtract two numbers and then print the result with echo.Examples
Inputnum1=10, num2=5
Output5
Inputnum1=100, num2=25
Output75
Inputnum1=7, num2=10
Output-3
How to Think About It
To subtract two numbers in Bash, first get the two numbers as input or variables, then use the arithmetic expansion syntax
$(( )) with the minus operator - to calculate the difference, and finally print the result.Algorithm
1
Get the first number and store it in a variable.2
Get the second number and store it in another variable.3
Calculate the difference using arithmetic expansion with the minus operator.4
Print the result to the screen.Code
bash
#!/bin/bash num1=15 num2=8 result=$((num1 - num2)) echo "$result"
Output
7
Dry Run
Let's trace subtracting 15 and 8 through the code
1
Assign num1
num1=15
2
Assign num2
num2=8
3
Calculate result
result=$((15 - 8)) = 7
4
Print result
echo 7
| Variable | Value |
|---|---|
| num1 | 15 |
| num2 | 8 |
| result | 7 |
Why This Works
Step 1: Arithmetic Expansion
The $(( )) syntax tells Bash to calculate the expression inside as a math operation.
Step 2: Subtraction Operator
Inside the arithmetic expansion, the - operator subtracts the second number from the first.
Step 3: Output Result
The echo command prints the calculated difference to the terminal.
Alternative Approaches
Using expr command
bash
#!/bin/bash num1=20 num2=5 result=$(expr $num1 - $num2) echo "$result"
Uses external command expr; less efficient but works in older shells.
Using let command
bash
#!/bin/bash num1=12 num2=7 let result=num1-num2 echo "$result"
Uses built-in let for arithmetic; simpler but less flexible for complex expressions.
Complexity: O(1) time, O(1) space
Time Complexity
Subtraction is a single arithmetic operation, so it runs in constant time.
Space Complexity
Only a few variables are used, so space usage is constant.
Which Approach is Fastest?
Using arithmetic expansion $(( )) is fastest as it is built into Bash, unlike external commands like expr.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic Expansion $(( )) | O(1) | O(1) | Fast, modern Bash scripts |
| expr command | O(1) | O(1) | Compatibility with older shells |
| let command | O(1) | O(1) | Simple arithmetic in Bash |
Always use
$(( )) for arithmetic in Bash for clarity and speed.Forgetting to use
$(( )) causes Bash to treat subtraction as a string, not math.