1

I am new to arrays in Bash scripting. I need to write a script which accepts an array from standard input on the command line. and outputs the sum of it to the user.

Here is the logic, but how can I convert it into shell script to be used in command line?

read -a array

tot=0
for i in ${array[@]}; do
  let tot+=$i
done

echo "Total: $tot"

Any help is appreciated.

Will
  • 24,082
  • 14
  • 97
  • 108
Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130
  • Can you show us an example usage of the desired script? – Leon Jul 12 '16 at 07:35
  • 1
    What do you mean by "accept an array"? Is the input simply a stream of numeric values? Is there some requirement that you store that stream in an array before you produce a sum? The typical solution to add a stream of values does not involve arrays at all. Are the values being entered on stdin or from the command line? The two are different, and the expression "from standard input on the command line" is incoherent. – William Pursell Jul 12 '16 at 11:38
  • @WilliamPursell yes the input is taken from STDIN – Vikram Anand Bhushan Jul 13 '16 at 06:13

2 Answers2

1

You're close! Try this instead:

IFS=$'\n' read -d '' -r -a array

total=0
for i in "${array[@]}"; do
    ((total += i))
done

When you're reading $array from stdin with read -a, you're only getting the first line.

IFS=$'\n' changes Bash's Internal Field Separator to the newline symbol (\n) so that each line is seen as a separate field, rather than looking for tokens separated by whitespace. -d '' makes read not stop reading at the end of each line. ((total += i)) is a shorter/cleaner way to do math.

Here's it running:

$ seq 1 10 | ./test.sh
Total: 55
Will
  • 24,082
  • 14
  • 97
  • 108
0
#!/bin/bash
calcArray() {
        local total=0
        for i ;do
           let total+=$i
        done
        echo "${total}"
}

From your terminal do this source scriptName . calcArray 1 2 3 4 5 Don't quote the args. In your .bashrc put source scriptName, so you can always run calcArray args , without source scriptName again

0.sh
  • 2,659
  • 16
  • 37