![](/img/trans.png)
[英]How to pipe input to a Bash while loop and preserve variables after loop ends
[英]How to get information from a while loop after a pipe in bash
从这个简单的例子:
$ 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.
有什么办法可以把它弄出来吗?
注意:我知道有更好/更简单的方法来完成这个特定的事情,但这只是一个简化的例子。 我的问题是如何在 pipe 之后从 while 循环中获取信息。
当禁用作业控制并启用lastpipe
选项时; 管道的最后一个组件在当前执行环境中运行。 看
$ x=foo
$ set +m # disables job control
$ shopt -s lastpipe
$ echo | x=bar
$ echo $x
bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.