How to add array elements in shell script

Let's write a shell script to add array elements in shell script.




Algorithm

1. Declare and initialize the array elements

2. Iterate the array using for loop

3. Add each array element

4. Print the result




Add array elements - Shell Script

#sum of array shell script

arr=(10 20 30 40 50)

sum=0

for i in ${arr[@]}
do
    sum=`expr $sum + $i`
done

echo $sum

Using ${arr[@]} or ${arr[*]}, we can access the all array elements.




Output

150


Topics You Might Like