From owner-freebsd-questions@FreeBSD.ORG Wed Jul 15 17:58:40 2009 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 E07B5106566C for ; Wed, 15 Jul 2009 17:58:40 +0000 (UTC) (envelope-from jhall@socket.net) Received: from mf5.socket.net (mf5b.socket.net [216.106.26.210]) by mx1.freebsd.org (Postfix) with ESMTP id C0FB18FC1E for ; Wed, 15 Jul 2009 17:58:40 +0000 (UTC) (envelope-from jhall@socket.net) Received: from jeflspare1.mo.loc (unknown [65.117.48.155]) by mf5.socket.net (Postfix) with ESMTP id 917E565397; Wed, 15 Jul 2009 12:58:39 -0500 (CDT) Message-Id: From: Jay Hall To: Dan Nelson In-Reply-To: <20090715055305.GG63413@dan.emsphone.com> Content-Type: text/plain; charset=US-ASCII; format=flowed; delsp=yes Content-Transfer-Encoding: 7bit Mime-Version: 1.0 (Apple Message framework v935.3) Date: Wed, 15 Jul 2009 12:58:39 -0500 References: <4A48C83B-A36C-417F-9F68-F1CB1BCDDC8F@socket.net> <142219524.01247634136492.JavaMail.root@bayleaf> <20090715055305.GG63413@dan.emsphone.com> X-Mailer: Apple Mail (2.935.3) Cc: Bryan Venteicher , freebsd-questions@freebsd.org Subject: Re: Bash and arrays 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: Wed, 15 Jul 2009 17:58:41 -0000 On Jul 15, 2009, at 12:53 AM, Dan Nelson wrote: > In the last episode (Jul 15), Bryan Venteicher said: >>> I thought I understood how arrays work in bash, but I have been >>> proven >>> wrong. I am reading lines from a file and placing them in an array. >>> However, when I am finished, the array has a length of 0. >>> >>> Following is the code I am using. >>> >>> #!/usr/local/bin/bash >>> COUNTER=0 >>> cat ./test_file.txt | while read LINE >>> do >>> echo ${LINE} >>> FOO[${COUNTER}]=${LINE} >>> COUNTER=`expr ${COUNTER} + 1` >>> done >>> >>> echo ${#FOO[@]} >>> echo ${#FOO[*]} >>> >>> >>> And, here is the output. >>> >>> test_file >>> file_size >>> 0 >>> 0 >>> >>> Thanks in advance for any help you can offer. >> >> The right hand side of the pipe is running in its own subshell so >> it has its own copy of FOO. >> >> One fix is >> #!/usr/local/bin/bash >> COUNTER=0 >> while read LINE >> do >> echo ${LINE} >> FOO[${COUNTER}]=${LINE} >> COUNTER=`expr ${COUNTER} + 1` >> done < ./test_file.txt > > Another alternative would be to use zsh, which makes sure that the > last > component of a pipeline is run in the current shell process so the > original > script would have worked. > > -- > Dan Nelson > dnelson@allantgroup.com > Thanks to everyone for their help. I had forgotten the right side of the pipe runs in its own subshell. Jay