Command line arguments for addition

Hi all,
I am trying to write a code for addition of n numbers which will be passed by the user as command line arguments.

I wrote the following code.

add=0
for (( i = 1 ; i <= $# ; i++ ))
do
add=`expr $i + $add`
done
#echo "sum is : $add"

input :

$./add.sh 12 32 14 25

Now the problem is the $i is giving values 1,2,3.... But i want the values inside command line variables $1, $2, $3......

So wat changes can i make to resolve the problems.

Thanks in advance.

Try:

set -A args "$@"
add=0
for (( i = 0 ; i < ${#args[*]} ; i++ ))
do
 ((add+=args))
done
echo "sum is : $add"

For your understanding:

set 12 67 18

echo $1
12

a=1
echo $a
1

eval 'echo $'$a
12

Thanks Elixir, But this code is giving me error.

./add.sh: line 1: set: -A: invalid option
set: usage: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
sum is : 0

I am using puTTy 0.61.

Please try the code below:

 
add=0
for i in $*
do
add=`expr $i + $add`
done
echo "sum is : $add"
 
sh a 12 32 14 25
sum is : 83
1 Like

This too should work.. hope this is simple..

add=0
for i in $@
do
add=`expr $i + $add`
done
echo "sum is: $add"

./add.sh 1 4 5
sum is: 10

1 Like

Which shell? I'd written that code for ksh93.

1 Like

Thanks Surendran, Arun it worked perfectly.

@Elixir, I am using Bash shell sir. and i will be very grateful if you could please explain what difference $@ and $* did to the code.

"$@" is all the positional parameters as separate strings
"$*" is all the positional parameters as one single string...

1 Like