Anthony Myers
Anthony Myers

Reputation: 25

Counting numbers in an array

I have been working on my script file and it is supposed to sum up a list of numbers and then count any numbers greater than 100 from the array. When I execute the script, my count is blank because it is only counting the last number in the array, which is 17 and is less than 100. I tested this by putting greater than 2 and when I run it, it displays the last number (17) only. I'm pretty new to creating if/then statements in shell so if anything looks out of place or if I'm missing something please let me know. Thank you.

Below is my code:

#!/bin/sh
sum=0
array=(12 43 16 55 243 312 17)
for i in ${array[@]}; do
    echo $i;
    let sum+=$i
done
echo Total = $sum
if [ $i -gt 2 ];  then
    echo $i
fi

Upvotes: 2

Views: 583

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80931

Do your check and keep count in the loop instead of after it.

#!/bin/sh
sum=0
array=(12 43 16 55 243 312 17)
for i in "${array[@]}"; do
    echo "$i";
    let sum+="$i"
    if [ $i -gt 2 ];  then
        echo "$i is greater than 2"
    fi
done
echo "Total = $sum"

Upvotes: 0

Roland Illig
Roland Illig

Reputation: 41625

You are using the variable i outside the for loop. The if clause should be inside the for loop.

count=0
for i in ${array[@]}; do
  if [ $i -gt 100 ]; then
    let count++
  fi
done

Upvotes: 2

Related Questions