1

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

sachin
  • 117
  • 2
  • 4
  • 6

2 Answers2

1

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

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
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)
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
  • 1
    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. – Karoly Horvath Oct 10 '11 at 22:54
  • 1
    @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 May 26 '15 at 08:31
  • 2
    @drevicko: it does *not*. you're probably running a subshell. if still in doubt, post a question. – Karoly Horvath May 26 '15 at 09:09
  • Hmm.. looks like you're right.. I posted [a question](http://stackoverflow.com/q/30458681/420867) on the strange behaviour I'm seeing – drevicko May 26 '15 at 12:33