Shell scripts: variable assignment within read loops

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


On Sun, 17 Aug 2008, David Wolfskill wrote:

[snipped]
> 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:

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

Cheers,
jan


-- 
jan grant, ISYS, University of Bristol. http://www.bris.ac.uk/
Tel +44 (0)117 3317661   http://ioctl.org/jan/
( echo "ouroboros"; cat ) > /dev/fd/0 # it's like talking to yourself sometimes


More information about the freebsd-questions mailing list