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 

#loop for sum in array

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

  let sum+=$i



echo "Sum: $sum"
  • 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 9 '18 at 0:21
  • Aside from which, this really isn't what shell scripts are for. See unix.stackexchange.com/a/341359/135943 – Wildcard Jan 9 '18 at 0:32

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)

for i in "${array1[@]}"; do
echo "Sum: $sum"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.