Bash Script to Find Sum of Even Numbers
if (( num % 2 == 0 )), and adds it to a sum variable; for example: sum=0; for num in {1..10}; do if (( num % 2 == 0 )); then ((sum+=num)); fi; done; echo $sum.Examples
How to Think About It
%, and if yes, add it to a running total. This way, you only add even numbers and ignore odd ones.Algorithm
Code
sum=0 for num in "$@"; do if (( num % 2 == 0 )); then ((sum+=num)) fi done echo "$sum"
Dry Run
Let's trace the input '1 2 3 4 5' through the code
Initialize sum
sum=0
Check number 1
1 % 2 = 1 (odd), sum remains 0
Check number 2
2 % 2 = 0 (even), sum = 0 + 2 = 2
Check number 3
3 % 2 = 1 (odd), sum remains 2
Check number 4
4 % 2 = 0 (even), sum = 2 + 4 = 6
Check number 5
5 % 2 = 1 (odd), sum remains 6
Output sum
Print 6
| Number | Is Even? | Sum After Step |
|---|---|---|
| 1 | No | 0 |
| 2 | Yes | 2 |
| 3 | No | 2 |
| 4 | Yes | 6 |
| 5 | No | 6 |
Why This Works
Step 1: Check even numbers
The script uses num % 2 == 0 to find even numbers because even numbers have no remainder when divided by 2.
Step 2: Add to sum
When a number is even, it is added to the sum variable using ((sum+=num)) which updates the total.
Step 3: Output result
After checking all numbers, the script prints the total sum of even numbers with echo.
Alternative Approaches
seq 1 10 | awk '{if ($1 % 2 == 0) sum += $1} END {print sum}'
sum=0 while read num; do if (( num % 2 == 0 )); then ((sum+=num)) fi done echo "$sum"
Complexity: O(n) time, O(1) space
Time Complexity
The script loops through each number once, so the time grows linearly with the number of inputs.
Space Complexity
Only a few variables are used regardless of input size, so space usage is constant.
Which Approach is Fastest?
The pure Bash loop is efficient and simple; using external tools like awk adds overhead but can be more concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash loop with arithmetic | O(n) | O(1) | Simple scripts with input arguments |
| seq with awk | O(n) | O(1) | Quick one-liners with piped input |
| while read loop | O(n) | O(1) | Reading from standard input or files |
((num % 2 == 0)) to quickly check if a number is even in Bash.(( )) for arithmetic evaluation causes errors in Bash.