2

I have a do while loop where I am adding a variable to itself

while read line 
do
      let variable=$variable+$someOtherVariable
done
    return $variable

When I echo the value of $variable I get no output ...

Is this the correct way to add some value back to the variable itself (i.e. i = i+j) Also, in the context of bash scripting what is the scope in this case..

2 Answers 2

1

return returns an "exit" code, a number, not what you are looking for. You should do an echo.

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

Comments

0

The problem is that the variable is not visible outside of the scope (the assignment is not propagated outside the loop).

The first way that comes to mind is to run the command in a subshell and forcing the loop to emit the variable:

variable=$(variable=0; while read line; do variable=$((variable+someOtherVariable)); done; echo $variable)

4 Comments

nope, it's visible outside of the loop scope. There's really no scope in bash unless you're inside a function or running a subshell.
@KarolyHorvath I beg to differ: a quick experiment in bash 4.2.25(1)-release (x86_64-pc-linux-gnu) reveals that a variable assigned within a loop regains its previous value after the done terminating the loop.
@drevicko: it does not. you're probably running a subshell. if still in doubt, post a question.
Hmm.. looks like you're right.. I posted a question on the strange behaviour I'm seeing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.