[英]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.