Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 15 Jul 2009 12:58:39 -0500
From:      Jay Hall <jhall@socket.net>
To:        Dan Nelson <dnelson@allantgroup.com>
Cc:        Bryan Venteicher <bryanv@daemoninthecloset.org>, freebsd-questions@freebsd.org
Subject:   Re: Bash and arrays
Message-ID:  <CC2CF886-C52B-442E-B863-D7113722799D@socket.net>
In-Reply-To: <20090715055305.GG63413@dan.emsphone.com>
References:  <4A48C83B-A36C-417F-9F68-F1CB1BCDDC8F@socket.net> <142219524.01247634136492.JavaMail.root@bayleaf> <20090715055305.GG63413@dan.emsphone.com>

next in thread | previous in thread | raw e-mail | index | archive | help

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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?CC2CF886-C52B-442E-B863-D7113722799D>