D.J.K. - 1 year ago 96

Bash Question

I made a loop to find the results of calculating each number from (1 to 10 mod 5) + 2

`for (( i = 0; i <= 10; i++))`

do

calculate=$(( i % 5 + 2 ))

echo "($i % 5) + 2 = " $calculate

done

average=$(($calculate/10))

echo $average`

My problem is fixing my code so that I can take all the results of the loop and find the average of them

Its returning back 0 for the average

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You have to keep a full total - `($calculate/10)`

is just the *last* iteration. Keep a running total initialized to zero before the loop `total = 0`

... then add the calculated value to the total in each iteration of the loop `total = $( $total + $calculate )`

Then the average is `total/10`

(not calculate/10).

```
#!/bin/bash
total=0
for (( i = 0; i <= 10; i++))
do
calculate=$(( i % 5 + 2 ))
total=$(( $total + $calculate ))
echo "($i % 5) + 2 = " $calculate
done
#average=$(($calculate/10))
average=$(($total/10))
echo $average
```