Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

linux - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...