Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to add the elements of an array that is defined by user input from the read -a command. How can I do that?

like image 251
BobbyT28 Avatar asked Nov 29 '12 21:11

BobbyT28


People also ask

How do you use an array sum?

S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.


2 Answers

read -a array
tot=0
for i in ${array[@]}; do
  let tot+=$i
done
echo "Total: $tot"
like image 130
perreal Avatar answered Oct 08 '22 04:10

perreal


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).

like image 38
gniourf_gniourf Avatar answered Oct 08 '22 03:10

gniourf_gniourf