How can I find the sum of the elements of an array in Bash? How can I find the sum of the elements of an array in Bash? unix unix

How can I find the sum of the elements of an array in Bash?


read -a arraytot=0for i in ${array[@]}; do  let tot+=$idoneecho "Total: $tot"


Given an array (of integers), here's a funny way to add its elements (in bash):

sum=$(IFS=+; echo "$((${array[*]}))")echo "Sum=$sum"

e.g.,

$ array=( 1337 -13 -666 -208 -408 )$ sum=$(IFS=+; echo "$((${array[*]}))")$ echo "$sum"42

Pro: No loop, no subshell!

Con: Only works with integers

Edit (2012/12/26).

As this post got bumped up, I wanted to share with you another funny way, using dc, which is then not restricted to just integers:

$ dc <<< '[+]sa[z2!>az2!>b]sb1 2 3 4 5 6 6 5 4 3 2 1lbxp'42

This wonderful line adds all the numbers. Neat, eh?

If your numbers are in an array array:

$ array=( 1 2 3 4 5 6 6 5 4 3 2 1 )$ dc <<< '[+]sa[z2!>az2!>b]sb'"${array[*]}lbxp"42

In fact there's a catch with negative numbers. The number '-42' should be given to dc as _42, so:

$ array=( -1.75 -2.75 -3.75 -4.75 -5.75 -6.75 -7.75 -8.75 )$ dc <<< '[+]sa[z2!>az2!>b]sb'"${array[*]//-/_}lbxp"-42.00

will do.

Pro: Works with floating points.

Con: Uses an external process (but there's no choice if you want to do non-integer arithmetic — but dc is probably the lightest for this task).


My code (which I actually utilize) is inspired by answer of gniourf_gniourf. I personally consider this more clear to read/comprehend, and to modify. Accepts also floating points, not just integers.

Sum values in array:

arr=( 1 2 3 4 5 6 7 8 9 10 )IFS='+' sum=$(echo "scale=1;${arr[*]}"|bc)echo $sum # 55

With small change, you can get the average of values:

arr=( 1 2 3 4 5 6 7 8 9 10 )IFS='+' avg=$(echo "scale=1;(${arr[*]})/${#arr[@]}"|bc)echo $avg # 5.5