【问题标题】:How to get information from a while loop after a pipe in bash如何在bash中的管道之后从while循环中获取信息
【发布时间】:2020-08-03 23:58:16
【问题描述】:

从这个简单的例子:

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

似乎管道字符启动了一个新的shell,它确实获得了变量x的副本,但是在管道的末尾,该值内的x的值不会被复制回外壳.

有什么办法可以把它弄出来吗?

注意:我知道有更好/更简单的方法来完成这个特定的事情,但这只是一个简化的例子。我的问题是如何在管道之后从 while 循环中获取信息。

【问题讨论】:

  • x="ls output: $(echo *)" 或更好:printf -v x '%q ' *; x="ls output: $x"

标签: bash while-loop pipe


【解决方案1】:

当作业控制被禁用,lastpipe 选项被启用时;管道的最后一个组件在当前执行环境中运行。见

$ x=foo
$ set +m # disables job control
$ shopt -s lastpipe
$ echo | x=bar
$ echo $x
bar

【讨论】:

  • 谢谢!不幸的是,lastpipe 显然是在 bash 4.2 中添加的,我正在运行 4.1.2。对于旧版本,请参阅here
猜你喜欢
  • 2016-12-16
  • 2019-08-18
  • 2022-12-24
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多