Understanding a script for sum

Hello,

How come the following script adds each numeric value to a total sum ?

x=$1 
func() 
{ 
for i in $1 $2 $3; do 
let x= $x+$i 
done } 

func "8 8 8" 9 9 

echo $x

A.How the program sums the string "8 8 8" if it`s only the first field value ($1)?
B.If we define x to be $1 (x=$1) then we wouldn't be doing "8 8 8" + "8 8 8" on the first iteration ?

That obviously is a (bourne) shell function. As you don't mention your shell's version, bash assumed.

man bash :

During expansion, the "multiword character" of $1 is lost, and the shell makes up this five item list: 8 8 8 9 9 across which the for loop iterates, resulting in 42 plus x's initial value. Be aware that the x=$1 assignment has nothing to do with the $1 that func() is called with; function get their own set of parameters when called.
And, remove the space in the let assignment.

1 Like

Thank you, so the x=$1 assignment doesn't serve any noticeable purpose in this script ?

B.In truth, the for loop doesn't iterates just three times for $1 $2 $3 as defined but rather one time for each existed item,total of five iterations in this case ?

Like RudiC mentioned, x=$1 Assigns the value of the first parameter with which the script is called to variable x
After this there are 5 iterations that add a number to variable x
So in the end variable x will contain the sum of 6 numbers.

So if you call the script like this:

./script 1

Then the outcome is 43

./script 2

renders 44

--
Also:
let is an old, non-standard way of doing this. It is better to use portable shell arithmetic. So instead of

let x=$x+$i

use

x=$((x+i))

--
In bash/ksh/zsh you can also use:

(( x+=i ))
1 Like