A variable modified inside a while loop is not remembered

echo -e $lines | while read line 

The while loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.

Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines will run in a subshell:

while read line
    if [[ "$line" == "second line" ]]
        echo "Variable \$foo updated to $foo inside if inside while loop"
    echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"

You can get rid of the rather ugly echo in the here-string above by expanding the backslash sequences immediately when assigning lines. The $'...' form of quoting can be used there:

lines=$'first line\nsecond line\nthird line'
while read line; do
done <<< "$lines"

Leave a Comment