Question

According the bash(1) man pages, when I run the following:

set -e
x=2
echo Start $x
while [ $((x--)) -gt 0 ]; do echo Loop $x; done | cat
echo End $x

The output will be:

Start 2
Loop 1
Loop 0
End 2

After the loop (runs as a subshell) the variable x reset to 2. But if I remove the pipe the x will be updated:

Start 2
Loop 1
Loop 0
End -1

I need to change the x but, I need the pipe too. Any idea how to get around this problem?

Was it helpful?

Solution

bash always (at least as of 4.2) runs all non-rightmost parts of a pipeline in a subshell. If the value of x needs to change in the calling shell, you must rewrite your code to avoid the pipeline.

One horrible-looking example:

# If you commit to one bash feature, may as well commit to them all:
#   Arithmetic compound: (( x-- > 0 ))
#   Process substitution: > >( cat )
while (( x-- > 0 )); do echo Loop $x; done > >( cat )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top