Subject: Re: appending to a shell variable inside a loop
To: None <brook@biology.nmsu.edu>
From: None <cube@cubidou.net>
List: netbsd-help
Date: 03/11/2004 17:04:46
On Thu, Mar 11, 2004 at 07:58:15AM -0700, brook@biology.nmsu.edu wrote:
> I am trying to write a shell script that will construct a list of
> words while inside a loop. Here is the logic I would have expected to
> work:
>
> #!/bin/sh
> LIST=""
> cat - | while true
^^^^^^^^^^^^^^^^^^
> do
> read WORD JUNK
> if [ $? -ne 0 ]; then break; fi
> LIST="$LIST $WORD"
> echo "LIST: $LIST"
> done
> echo "final LIST: $LIST"
>
> The problem is that the final value of $LIST is empty, though within
> the loop the value grows as expected. That is, the assignment inside
> the loop seems to have no effect on the outermost $LIST. Adding
> export does not seem to matter.
>
> I must be missing something obvious about shell variables. How can
> this be done?
Using a pipe here means you're launching the while loop in a sub-shell.
Hence, $LIST inside the loop is not the same as the external $LIST, and
get lost when the sub-shell exits.
The 'cat -' here is really useless, just remove it and 'read' will take
its input from the standard input anyway.
If you really need a cat here, you'll have to make the sub-shell return
a value on the standard output, and assign it, or something like that.
Quentin Garnier.