bash piping prevents global variable assignment

All components of a pipeline (if more than one) are executed in a subshell, and their variable assignments do not persist to the main shell.

The reason for this is that bash does not support real multithreading (with concurrent access to variables), only subprocesses which run in parallel.


How to avoid this:

You have to do any variable assignments you want to retain in the main bash process (or find some way to transfer them there). The bash way of doing this would be not to use a pipe, but use process substitution instead:

f > >( cat )

Of course, this will not help if you need to do variable assignments in both processes of a pipe. Then you have to think of a better mechanism instead (maybe coprocesses, and output the variables somewhere?)

Leave a Comment