On Sat, 9 Jan 2010 08:51:31 +0100 Matthias Kilian
<[email protected]> wrote:
> n Fri, Jan 08, 2010 at 10:18:39PM -0800, J.C. Roberts wrote:
> > When you append to a variable within a 'for' loop, the changes are
> > exist after the loop ends, but if you do the same within a 'while'
> > loop, the changes are lost?
> [...]
> > # Now we try the same type of thing with the 'while' loop.
> > cat list.txt | while read -r WNAME; do
> [...]
>
> That while loop is running in a separate process; the parent process
> won't see any variable changes made in the loop.
>
> Ciao,
> Kili
Bah! I totally missed that. Makes sense now. Thanks Kili.
If I use redirection rather than piping for input to the `while` loop,
it is not a separate process, and works like the 'for' loop.
****************************************************************
while read -r WNAME; do
if [[ -z $WLIST ]]; then
WLIST="$WNAME";
else
WLIST="$WLIST $WNAME";
fi
printf "WLIST: %s\n" "$WLIST";
done < list.txt
****************************************************************
If I wanted to use the other method with "cat list.txt |", I'd have to
use a co-process &| to talk to the 'while' loop (and "read -p"/"print
-p") and get the changes to the variables.
--
J.C. Roberts