'How to get information from a while loop after a pipe in bash
From this trivial example:
$ x="ls output: "
$ ls | while read line; do x="$x $line"; echo $x; done
ls output: a
ls output: a b
ls output: a b c
ls output: a b c d
$ echo $x
ls output:
it seems the pipe character starts a new shell, which does get a copy of the variable x
, but at the end of the pipe, the value of x
inside that value is not copied back to the outer shell.
Is there any way I can get it out?
Note: I know there are much better / simpler ways to get this particular thing done, but this is just a simplified example. My question is how to get information out of a while loop after a pipe.
Solution 1:[1]
When job control is disabled and the lastpipe
option is enabled, the last component of a pipeline is run in the current execution environment. See
$ x=foo
$ set +m # disables job control
$ shopt -s lastpipe
$ echo | x=bar
$ echo $x
bar
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |