kenJackson
Member
If you've ever tried to use a while-loop like this, you've experienced some frustration.
Where I'm using this file named db:
When you run it, you get this result:
The problem is that since I'm piping into the while loop, it's run in a subprocess so changes to variables don't affect the parent's environment.
In this case it can be solved by redirection like this, but it seems all too easy to accidentally end up with all or part of the loop in a subprocess some other way, which results in unexpected failures.
But here's what I just learned.
This is a new technique, at least to me. (Has anyone used this before?)
Notice the "exec 7< db" opens the file, "<&7" redirects input, and "exec 7<&-" closes it. Any available file descriptor number greater than 2 can be used.
Of course it's still possible to accidentally put something into a subprocess, but this just seems a little cleaner to me.
Code:
#!/bin/sh
RESULT=
cat db | while read index color; do
test "$index" = 2 && RESULT="$color"
done
echo "Index 2 is \"$RESULT\""
Code:
1 red
2 green
3 blue
Code:
Index 2 is ""
In this case it can be solved by redirection like this, but it seems all too easy to accidentally end up with all or part of the loop in a subprocess some other way, which results in unexpected failures.
Code:
done < db
But here's what I just learned.
This is a new technique, at least to me. (Has anyone used this before?)
Code:
#!/bin/sh
RESULT=
exec 7< db
while read index color <&7; do
test "$index" = 2 && RESULT="$color"
done
exec 7<&-
echo "Index 2 is \"$RESULT\""
Of course it's still possible to accidentally put something into a subprocess, but this just seems a little cleaner to me.