Ubuntu – How to add integers in an array

bashcommand linescripts

I'm trying to add some number in an array.

Example:

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

I've done it this way but I want to use an array and then sum up the numbers in a shell script.

num1=2
num2=4
num3=8
num4=10
num5=12
num6=14
num7=16
num8=18
num9=20
sum=$((num1+num2+num3+num4+num5+num6+num7+num8+num9))
echo "The sum is: $sum"

Best Answer

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