From owner-freebsd-questions@FreeBSD.ORG Thu Aug 21 13:59:19 2008 Return-Path: Delivered-To: freebsd-questions@freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id AF9681065691 for ; Thu, 21 Aug 2008 13:59:19 +0000 (UTC) (envelope-from jan.grant@bristol.ac.uk) Received: from dirg.bris.ac.uk (dirg.bris.ac.uk [137.222.10.102]) by mx1.freebsd.org (Postfix) with ESMTP id 712AF8FC16 for ; Thu, 21 Aug 2008 13:59:19 +0000 (UTC) (envelope-from jan.grant@bristol.ac.uk) Received: from mail.ilrt.bris.ac.uk ([137.222.16.62]) by dirg.bris.ac.uk with esmtp (Exim 4.69) (envelope-from ) id 1KWARU-0005mx-Uo; Thu, 21 Aug 2008 14:43:15 +0100 Received: from cse-jg.cse.bris.ac.uk ([137.222.12.37]:64830) by mail.ilrt.bris.ac.uk with esmtps (TLS-1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.63) (envelope-from ) id 1KWARJ-0002v1-VY; Thu, 21 Aug 2008 14:43:02 +0100 Date: Thu, 21 Aug 2008 14:43:01 +0100 (BST) From: Jan Grant X-X-Sender: cmjg@tribble.ilrt.bris.ac.uk To: David Wolfskill , freebsd-questions@freebsd.org In-Reply-To: <20080818013328.GY44815@bunrab.catwhisker.org> Message-ID: <20080821144054.X1910@tribble.ilrt.bris.ac.uk> References: <20080818013328.GY44815@bunrab.catwhisker.org> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-ILRT-MailScanner: Found to be clean X-ILRT-MailScanner-SpamCheck: not spam, SpamAssassin (not cached, score=-3.011, required 5, ALL_TRUSTED -1.80, AWL 0.79, BAYES_00 -2.60, J_CHICKENPOX_83 0.60) X-ILRT-MailScanner-From: jan.grant@bristol.ac.uk X-Spam-Status: No X-Spam-Score: -0.8 X-Spam-Level: / Cc: Subject: Re: Shell scripts: variable assignment within read loops X-BeenThere: freebsd-questions@freebsd.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: User questions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Thu, 21 Aug 2008 13:59:19 -0000 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