Shell scripts: variable assignment within read loops

Jan Grant jan.grant at
Thu Aug 21 13:59:19 UTC 2008

On Sun, 17 Aug 2008, David Wolfskill wrote:

> will assign to foo the value of the bar variable form the last record
> read (in FreeBSD 6.3-STABLE, at least), the following fails to do so:
> 	foo=""
> 	cat $filename | while read bar ... ; do
> 	 ...
> 	  foo=$bar
> 	 ...
> 	done
> 	echo $foo
> Well, that's not *quite* accurate:the assignment is done all right, but
> in the latter case, it appears to be done in a subshell, so by the time
> we get to the "echo" statement, any variable assignments from within the
> read loop have vanished.

You've already defined the reason behind this. Since subshells for parts 
of pipelines aren't guaranteed, you need something more clever. Assuming 
you're only interested in the _last_ value of foo, you could try this:

	cat $filename | (
		while read bar; do
		echo $foo
	) )


jan grant, ISYS, University of Bristol.
Tel +44 (0)117 3317661
( echo "ouroboros"; cat ) > /dev/fd/0 # it's like talking to yourself sometimes

More information about the freebsd-questions mailing list