在bash中无法使用while和pipe的变量 [英] Can't use a variable out of while and pipe in bash

查看:159
本文介绍了在bash中无法使用while和pipe的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的代码

var="before"  
echo "$someString" | sed '$someRegex' | while read line 
do
    if [ $condition ]; then
        var="after"
        echo "$var" #first echo
    fi 
done 
echo "$var" #second echo

这里首先回显后,但第二个是之前。如何在之后进行第二个回显打印。我认为这是因为管道购买我不知道怎么弄清楚。

Here first echo print "after", but second is "before". How can I make second echo print "after". I think it is because of pipe buy I don't know how figure out.

感谢任何解决方案...

Thanks for any solutions...

回答编辑:

我更正了它,它的工作正常。感谢eugene你的有用答案

I corrected it and it works fine. Thanks eugene for your useful answer

var="before"  
while read line 
do
    if [ $condition ]; then
        var="after"
        echo "$var" #first echo
    fi 
done < <(echo "$someString" | sed '$someRegex')
echo "$var" #second echo


推荐答案

这个行为的原因是,当$ code> while 循环在子shell中运行时,它是管道的一部分。对于上述循环,将创建一个带有自己的变量 var 副本的新subshel​​l。

The reason for this behaviour is that a while loop runs in a subshell when it's part of a pipeline. For the while loop above, a new subshell with its own copy of the variable var is created.

有关可能的解决方法,请参阅此文章:我在一个循环中设置变量这是在管道中。为什么循环终止后它们会消失?或者,为什么我不能管道数据读取?

See this article for possible workarounds: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?.

这篇关于在bash中无法使用while和pipe的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆