Date: Thu, 21 Aug 2008 14:43:01 +0100 (BST) From: Jan Grant <jan.grant@bristol.ac.uk> To: David Wolfskill <david@catwhisker.org>, freebsd-questions@freebsd.org Subject: Re: Shell scripts: variable assignment within read loops Message-ID: <20080821144054.X1910@tribble.ilrt.bris.ac.uk> In-Reply-To: <20080818013328.GY44815@bunrab.catwhisker.org> References: <20080818013328.GY44815@bunrab.catwhisker.org>
next in thread | previous in thread | raw e-mail | index | archive | help
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
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20080821144054.X1910>