Bash variable scope Bash variable scope bash bash

Bash variable scope


Because you're piping into the while loop, a sub-shell is created to run the while loop.

Now this child process has its own copy of the environment and can't pass anyvariables back to its parent (as in any unix process).

Therefore you'll need to restructure so that you're not piping into the loop.Alternatively you could run in a function, for example, and echo the value youwant returned from the sub-process.

http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL


The problem is that processes put together with a pipe are executed in subshells (and therefore have their own environment). Whatever happens within the while does not affect anything outside of the pipe.

Your specific example can be solved by rewriting the pipe to

while ... do ... done <<< "$OUTPUT"

or perhaps

while ... do ... done < <(echo "$OUTPUT")


This should work as well (because echo and while are in same subshell):

#!/bin/bashcat /tmp/randomFile | (while read linedo    LINE="$LINE $line"done && echo $LINE )