开发者

Can't use a variable out of while and pipe in bash

I have a code like that

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...

answer edit:

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


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?.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜