0

I was writing a script, and ran into a problem where my variable will not stay set when I modify it from inside of a | while loop. To illustrate, I wrote this example:

#!/bin/bash

thevar="Foo"

grep "somestring" testfile.txt | while IFS= read -r line; do
    thevar+=" bar"
    echo "The var is now: $thevar"
done

echo+="But as soon as we get out of the while,the var goes back to $thevar"

Which outputs:

The var is now: Foo bar
But as soon as we get out of the while,the var goes back to Foo

Why is this happening, and what can I do to keep my variable?

Questionmark
  • 3,945

0 Answers0