How can I add integers in an array

You can do:

$ array=( 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

$ echo "${array[@]/,/+}" | bc               
110
  • ${array[@]/,/+} is a parameter expansion pattern that replaces all , with + in all elements of the array

  • Then bc simply does the addition

Let's break it up a bit for clarification:

$ array=( 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

$ echo "${array[@]/,/+}"                     
2+ 4+ 6+ 8+ 10+ 12+ 14+ 16+ 18+ 20

$ echo "${array[@]/,/+}" | bc
110

num1=2
num2=4
num3=8
array=($num1 $num2 $num3)
declare -i sum
IFS=+ sum="${array[*]}"
echo $sum

Output:

14

See: help declare


In Python it's very simple to add a list of numbers.

$ python -c 'print sum([1,2,3])'

Outputs 6.


Using a loop in Bash:

#!/bin/bash

nums=(1 2 3)
total=0
for n in ${nums[@]}
do
  (( total += n ))
done
echo $total

Outputs 6.


One could also use awk to perform the looping summation:

$ echo "${arr[@]}"
1 2 3
$ awk 'BEGIN{for (arg in ARGV) sum += arg;print sum}' "${arr[@]}"
6