-1

I am trying to create a script where the sum of the array is what prints but my results just end up showing me "Sum: 0"

Here is my script so far.

Any help in correcting this would be appreciated.

#! /bin/bash

declare -a array1={1 2 3 4}

#read array 
read -a array1

#set sum to zero 
sum=0

#loop for sum in array

for i in ${array1[@]}; do

  let sum+=$i

done

#print

echo "Sum: $sum"
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 2
    The declare doesn't work, array assignments take parenthesis, not braces, though you're not using the assigned array anyway, since you read over it. Also you should quote the array expansion, "${array1[@]}". But other than that, it does count the sum of the values entered, I don't see a problem in that. – ilkkachu Jan 09 '18 at 00:21
  • Aside from which, this really isn't what shell scripts are for. See https://unix.stackexchange.com/a/341359/135943 – Wildcard Jan 09 '18 at 00:32

1 Answers1

2

An array require the use of (…) in bash.
The array doesn't need to be read if it was already declared.
The ${array[@]} expansion require quotes to work correctly:

declare -a array1=(1 2 3 4)

sum=0
for i in "${array1[@]}"; do
  ((sum+=$i))
done
echo "Sum: $sum"