0

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.

PieterNuyts
  • 496
  • 5
  • 20

1 Answers1

3

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
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • Thanks! Unfortunately `lastpipe` was apparently added in bash 4.2 and I'm running 4.1.2. For older versions, see [here](https://stackoverflow.com/questions/36340599/how-does-shopt-s-lastpipe-affect-bash-script-behavior). – PieterNuyts Apr 21 '20 at 11:27