在 bash 中读取多行而不产生新的子shell?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2376031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading multiple lines in bash without spawning a new subshell?
提问by swampsjohn
I'm trying to do something like
我正在尝试做类似的事情
var=0
grep "foo" bar | while read line; do
var=1
done
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.
不幸的是,这不起作用,因为管道导致 while 在子shell中运行。有一个更好的方法吗?如果有其他解决方案,我不需要使用“阅读”。
I've looked at Bash variable scopewhich is similar, but I couldn't get anything that worked from it.
我看过类似的Bash 变量范围,但我无法从中得到任何有用的东西。
回答by Kaleb Pederson
If you really are doing something that simplistic, you don't even need the while readloop. The following would work:
如果你真的在做一些简单的事情,你甚至不需要while read循环。以下将起作用:
VAR=0
grep "foo" bar && VAR=1
# ...
If you really do need the loop, because other things are happening in the loop, you can redirect from a <( commands )process substitution:
如果您确实需要循环,因为循环中正在发生其他事情,您可以从<( commands )进程替换重定向:
VAR=0
while read line ; do
VAR=1
# do other stuff
done < <(grep "foo" bar)
回答by ghostdog74
then don't use pipe ,and lose the grep
然后不要使用管道,并失去 grep
var=1
while read line
do
case "$line" in
*foo* ) var=1
esac
done <"file"
echo "var after: $var"

