Issues with script for adding numbers

I am having issues submitting my script right now. I wonder if any of you have any ideas on why it is not taking it as it is working currently? It wants to add 6, 9, -4 and 7 together and my script is doing that.. Maybe there are ways to improve it? Any ideas would help out a lot.

``````#!/bin/bash

sum=0

for number in \$1 \$2 \$3 \$4
do
sum=\$((\$1 + \$2 + \$3 + \$4))
echo \$number

done

echo \$sum
``````
• Why are you looping across the positional parameters and summing all of them up four times? What happens with your script as written if you only give it three values to add? Mar 23, 2018 at 19:13
• Why the loop? `sum=\$((\$1 + \$2 + \$3 + \$4))` is enough IMHO. Mar 23, 2018 at 19:14
• I suggest you please take a look at this Q/A on AU as you highly need to have a sum function here. Mar 23, 2018 at 19:22

If you only want to add 4 numbers, this should be enough:

``````sum() {
printf '%d\n' "\$(( \$1 + \$2 + \$3 + \$4 ))"
}
``````

Or if you want to add an arbitrary amount of numbers:

``````sum() {
local number sum

for number; do
(( sum += number ))
done

printf '%d\n' "\$sum"
}
``````

Make the shell work for you. And use external utilities when called for.

``````#!/bin/bash
IFS=+
echo "\$*" | bc
``````

There is no need to loop if you know you're always going to get four integers on the command line:

``````#!/bin/sh

sum=\$(( \$1 + \$2 + \$3 + \$4 ))
printf 'sum is %d\n' "\$sum"
``````

Alternatively, just

``````#!/bin/sh

printf 'sum is %d\n' "\$(( \$1 + \$2 + \$3 + \$4 ))"
``````

To support an arbitrary number of argument, you will need to loop:

``````#!/bin/sh

while [ "\$#" -gt 0 ]; do
sum=\$(( sum + \$1 ))
shift
done

printf 'sum is %d\n' "\$sum"
``````

This script will iterate over its command line arguments, adding the first one to the `sum` variable and shifting it off the list of command line arguments, until no arguments are left. The `\$#` variable expansion will expand to the number of command line arguments, while `shift` will remove `\$1` from the list, shifting `\$2` into its place (and `\$3` into `\$2` etc.).

Alternatively:

``````#!/bin/sh

for num do
sum=\$(( sum + num ))
done

printf 'sum is %d\n' "\$sum"
``````

Instead of constantly shifting the list of command line arguments, this leaves the list untouch and instead iterates over it, adding each one to `sum` in turn.

The `for num do` loop head may also be written `for num in "\$@"; do`.