Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 15 Jul 2009 00:02:16 -0500 (CDT)
From:      Bryan Venteicher <bryanv@daemoninthecloset.org>
To:        Jay Hall <jhall@socket.net>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Bash and arrays
Message-ID:  <142219524.01247634136492.JavaMail.root@bayleaf>
In-Reply-To: <4A48C83B-A36C-417F-9F68-F1CB1BCDDC8F@socket.net>

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

----- Jay Hall <jhall@socket.net> wrote:
> Ladies and Gentlemen,
> 
> 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

> 
> 
> Jay
> _______________________________________________
> freebsd-questions@freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-questions
> To unsubscribe, send any mail to "freebsd-questions-unsubscribe@freebsd.org"




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?142219524.01247634136492.JavaMail.root>