3

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

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.