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
.
sum=$(($1 + $2 + $3 + $4))
is enough IMHO.