The Ins and Outs of Redirected I/O Loops

The Bourne shell usually runs a loop with redirected input or output () in a subshell (). For the formprog script in article , this means, among other things, that:

Greg Ubben sent me two other ways that he prefers. The first one depends on having a read that accepts redirection on its command line, which most do these days. The second works when you can put the usage in the same scope (within the curly braces ()) as the redirection:

exec 3< file {
 while read line <&3 while read line do do var=value var=value done done exec 3<&- echo "var = $var" echo "var = $var"
}
< file

Putting the loop inside a function and redirecting into the function also seems to avoid the subshell problem. But don't take my (our) word for it: test it on the shell you'll be using.

- JP