【发布时间】: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