0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Sum of Array Elements

Use a loop to add each element of the array to a sum variable like this: sum=0; for i in "${array[@]}"; do ((sum+=i)); done; echo $sum.
📋

Examples

Inputarray=(1 2 3 4 5)
Output15
Inputarray=(10 20 30)
Output60
Inputarray=()
Output0
🧠

How to Think About It

To find the sum of array elements, start with a total of zero and add each number in the array one by one. This way, you accumulate the total sum by visiting each element exactly once.
📐

Algorithm

1
Initialize a variable sum to 0
2
Loop through each element in the array
3
Add the current element's value to sum
4
After the loop ends, output the sum
💻

Code

bash
array=(1 2 3 4 5)
sum=0
for i in "${array[@]}"; do
  ((sum+=i))
done
echo $sum
Output
15
🔍

Dry Run

Let's trace the array (1 2 3 4 5) through the code

1

Initialize sum

sum=0

2

Add first element

sum=0+1=1

3

Add second element

sum=1+2=3

4

Add third element

sum=3+3=6

5

Add fourth element

sum=6+4=10

6

Add fifth element

sum=10+5=15

IterationCurrent ElementSum After Addition
111
223
336
4410
5515
💡

Why This Works

Step 1: Initialize sum

We start with sum=0 because we want to add numbers starting from zero.

Step 2: Loop through array

The for loop goes through each element in the array one by one.

Step 3: Add elements

Inside the loop, ((sum+=i)) adds the current element to the total sum.

Step 4: Output result

After the loop finishes, echo $sum prints the total sum.

🔄

Alternative Approaches

Using while loop with index
bash
array=(1 2 3 4 5)
sum=0
index=0
while [ $index -lt ${#array[@]} ]; do
  ((sum+=array[index]))
  ((index++))
done
echo $sum
This uses a while loop and index to access elements, which is more manual but useful if you need index control.
Using printf and awk
bash
array=(1 2 3 4 5)
printf "%s\n" "${array[@]}" | awk '{sum+=$1} END {print sum}'
This pipes array elements to awk for summing, which is concise but depends on external tools.

Complexity: O(n) time, O(1) space

Time Complexity

The script loops once through all n elements, so time grows linearly with array size.

Space Complexity

Only a few variables are used regardless of array size, so space is constant.

Which Approach is Fastest?

The simple for-loop with arithmetic is fastest and uses no external commands, unlike the awk method.

ApproachTimeSpaceBest For
For-loop with arithmeticO(n)O(1)Simple, fast, pure Bash
While loop with indexO(n)O(1)When index control is needed
Printf with awkO(n)O(1)Concise but uses external tool
💡
Always quote array expansions like "${array[@]}" to handle elements safely.
⚠️
Forgetting to initialize sum to zero causes incorrect results or errors.