如何在bash中进行管道操作后从while循环中获取信息

问题描述 投票:0回答:1

从这个简单的例子:

$ 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:

似乎管道字符启动了一个新的外壳,该外壳确实获得了变量x的副本,但是在管道的末尾,该值内的x的值并未复制回到外壳中。

有什么办法可以解决?

注意:我知道有更好/更简单的方法可以完成此特定操作,但这只是一个简化的示例。我的问题是如何在管道后的while循环中获取信息。

bash while-loop pipe
1个回答
0
投票

禁用作业控制,并且设置了lastpipe选项;管道的最后一个组件在当前执行环境中运行。参见

$ x=foo
$
$ set +m
$ shopt -s lastpipe
$
$ echo | x=bar
$ echo $x
bar
© www.soinside.com 2019 - 2024. All rights reserved.