Bash Script to Add Two Numbers with Output Example
Use a Bash script with
read to get two numbers and sum=$((num1 + num2)) to add them, then print the result with echo.Examples
Input3 and 5
OutputSum is 8
Input0 and 0
OutputSum is 0
Input-2 and 7
OutputSum is 5
How to Think About It
To add two numbers in Bash, first get the numbers from the user or variables, then use the arithmetic expansion
$(( )) to calculate their sum, and finally print the result with echo.Algorithm
1
Get the first number from the user2
Get the second number from the user3
Add the two numbers using arithmetic expansion4
Print the sumCode
bash
#!/bin/bash # Ask user for first number read -p "Enter first number: " num1 # Ask user for second number read -p "Enter second number: " num2 # Calculate sum sum=$((num1 + num2)) # Print the result echo "Sum is $sum"
Output
Enter first number: 3
Enter second number: 5
Sum is 8
Dry Run
Let's trace adding 3 and 5 through the code
1
Read first number
num1 = 3
2
Read second number
num2 = 5
3
Calculate sum
sum = 3 + 5 = 8
4
Print result
Output: Sum is 8
| Step | Variable | Value |
|---|---|---|
| 1 | num1 | 3 |
| 2 | num2 | 5 |
| 3 | sum | 8 |
Why This Works
Step 1: Reading input
The read command waits for user input and stores it in variables num1 and num2.
Step 2: Adding numbers
The arithmetic expansion $((num1 + num2)) calculates the sum of the two numbers.
Step 3: Displaying output
The echo command prints the sum with a message to the terminal.
Alternative Approaches
Using command line arguments
bash
#!/bin/bash num1=$1 num2=$2 sum=$((num1 + num2)) echo "Sum is $sum"
This method adds numbers passed as arguments when running the script, making it faster for automation but less interactive.
Using expr command
bash
#!/bin/bash read -p "Enter first number: " num1 read -p "Enter second number: " num2 sum=$(expr $num1 + $num2) echo "Sum is $sum"
Uses the older <code>expr</code> command for addition; less modern but compatible with very old shells.
Complexity: O(1) time, O(1) space
Time Complexity
Adding two numbers is a constant time operation, so the time complexity is O(1).
Space Complexity
The script uses a fixed number of variables, so space complexity is O(1).
Which Approach is Fastest?
Using arithmetic expansion $(( )) is faster and more readable than expr and better for interactive scripts than command line arguments.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic Expansion | O(1) | O(1) | Interactive scripts, readability |
| Command Line Arguments | O(1) | O(1) | Automation, scripting with parameters |
| expr Command | O(1) | O(1) | Legacy shell compatibility |
Always use
$(( )) for arithmetic in Bash for clear and efficient calculations.Forgetting to use
$(( )) causes Bash to treat numbers as strings, leading to incorrect results.