We have answer of your question!

100% solved queries, no empty question

Question: Global variable is reset if loop send output to pipe


0

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?

Question author Udi | Source

Answer


1


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 )
Answer author Chepner

Tickanswer.com is providing the only single recommended solution of the question Global variable is reset if loop send output to pipe under the categories i.e bash , variables , loops , subshell , . Our team of experts filter the best solution for you.

Related Search Queries:


You may also add your answer

Thanks for contributing an answer to Tick Answer!