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?
echo "${thevar[@]}"
. Also that isn't how you add an element to an array. Use:thevar+=('bar')
. – jesse_b Aug 10 '17 at 16:27thevar="$thevar bar"
– jesse_b Aug 10 '17 at 16:29