up vote 0 down vote favorite
share [g+] share [fb]

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..

link|improve this question

75% accept rate
feedback

2 Answers

up vote 0 down vote accepted

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)
link|improve this answer
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. – yi_H Oct 10 '11 at 22:54
feedback

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

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.