阅读在bash多行不产卵一个新的子shell? [英] Reading multiple lines in bash without spawning a new subshell?
问题描述
我试图做这样的事情。
var=0
grep "foo" bar | while read line; do
var=1
done
不幸的是,这并不工作,因为管道导致,而在一个子shell中运行。有没有更好的方式来做到这一点?我并不需要使用读,如果有另一种解决方案。
Unfortunately this doesn't work since the pipe causes the while to run in a subshell. Is there a better way to do this? I don't need to use "read" if there's another solution.
我看了<一个href=\"http://stackoverflow.com/questions/124167/bash-variable-scope\">http://stackoverflow.com/questions/124167/bash-variable-scope这是类似的,但我无法得到任何来自它的工作。
I've looked at http://stackoverflow.com/questions/124167/bash-variable-scope which is similar, but I couldn't get anything that worked from it.
推荐答案
如果你真的做的事情简单化,你甚至不需要在而读
循环。下面将工作:
If you really are doing something that simplistic, you don't even need the while read
loop. The following would work:
VAR=0
grep "foo" bar && VAR=1
# ...
如果你真的需要循环,因为其他东西都在循环中发生的事情,你可以从&LT重定向(命令)
进程替换:
If you really do need the loop, because other things are happening in the loop, you can redirect from a <( commands )
process substitution:
VAR=0
while read line ; do
VAR=1
# do other stuff
done < <(grep "foo" bar)
这篇关于阅读在bash多行不产卵一个新的子shell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!