简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM