0

I have this:

sum() for i in $@; do ((tot += 4)); echo $tot;done

Now, how do i reset the tot variable before the for-loop?

I tried:

sum() tot = 0; for i in $@; do ((tot += 4)); echo $tot;done

sum() tot = 0;done; for i in $@; do ((tot += 4)); echo $tot;done

sum() tot = 0 for i in $@; do ((tot += 4)); echo $tot;done

sum() ((tot = 0)) for i in $@; do ((tot += 4)); echo $tot;done

2 Answers 2

2

A function definition requires a single compound command as its body. This is legal

sum() for i in $@; do ((tot += 4)); echo $tot;done

because your for loop is that single compound command. As soon as you try to add another command (in this case, the assignment to tot), you need to ensure both that command and the for loop are combined in another compound command.

The usual way to define a function is to always use a brace group (or in certain situations, a subshell (...)), even if the only command inside the brace group is another compound command. Here, the brace group allows you to add your assignment statement to the body of the function:

sum () {
    tot=0
    for i in "$@"; do ((tot += 4)); echo "$tot"; done
}

Your first two attempts are errors because a single assignment statement is not a valid function body.

Your third attempt is an error because compound commands (unlike simple commands) cannot be preceded by a variable assignment.

Your fourth attempt is syntactically legal; it defines a function sum that sets the value of tot to 0. The for loop is executed after the function is defined, rather than being part of the function definition.

Sign up to request clarification or add additional context in comments.

Comments

2

You have to make the variable tot local to the function with the local keyword:

sum() { local tot; for i in $@; do ((tot += 4)); echo $tot;done; }

optionally, when defining a local variable, you can also set an initial value:

sum() { local tot=0; for i in $@; do ((tot += 4)); echo $tot;done; }

but this is optional here.

2 Comments

It might be a good idea to make tot a local variable, but that doesn't actually solve the original problem. Ensuring the assignment and the for loop are all part of a single compound command (inside the {...}) does.
Might as well make the i variable local too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.