Okay, so I’m trying to parse a file that outputs in columns what I need in rows, and I can’t get this while loop to work, and I’m really stumped.
Interestingly, doing almost the exact same thing with a for loop does work. Can someone please explain what’s going on here?
This…
e=""
for f in 1 2 3
do
echo $f
e="$e.$f"
done
echo $e
Outputs:
1
2
3
.1.2.3
But this…
e=""
echo "1
2
3" | while read f
do
echo $f
e="$e.$f"
done
echo $e
Outputs:
1
2
3
Clearly both loops have 1, 2, or 3 in $f when they get to e="$e.$f", so what the heck is going on that the second one doesn’t work?
I can’t tell you how many times I’ve had to pull this bug out of someone’s code.
Basically the pipe generates a forked process. e is set in the forked process, but when that terminates (at the end of the wile loop) the parent process does not know that e has changed. In short, never set a variable in a command involving a pipe. It will not be set when the pipe finishes. Shorter… Don’t use pipes if they can be avoided.