简体   繁体   English

如何在 bash 中的 pipe 之后从 while 循环中获取信息

[英]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. 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.我的问题是如何在 pipe 之后从 while 循环中获取信息。

When job control is disabled, and the lastpipe option is enabled;当禁用作业控制并启用lastpipe选项时; 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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