[NBLUG/talk] Arrays in Bash

Micxz micxz at micxz.com
Fri May 13 09:55:09 PDT 2011


You may have already looked at the abs guide. I'm not sure it this will 
work for you but there is printf check out example Example 27-2 
(http://tldp.org/LDP/abs/html/arrays.html)

--
Micxz

On 5/13/11 6:15 AM, Andrew wrote:
> I'm stumped. I'm trying to write a Bash script that utilizes
> multiple arrays to organize data, and I want to use a for loop to
> access the data stored in those arrays. On the first pass through
> the loop, I want to access the data in the first array. On the
> second pass, I want to access the data in the second array. And
> so on.
>
> I was hoping to do so with something like this (simplified) code:
>
> ################################
>
> ARRAY_ONE=(foo bar baz)
> ARRAY_TWO=(Alice Bob Carol)
>
> for i in ARRAY_ONE ARRAY_TWO
> do
>    echo ${i}         # Print the array name
>    echo "${i[2]}"    # Print the third element in the array
> done
>
> ################################
>
> The problem is in the second echo statement. I want the stuff
> inside the quotes to expand to $ARRAY_ONE[2] on the first pass
> through the loop, and $ARRAY_TWO[2] on the second, and then (and
> this is the important part) _access_ the referenced elements. But
> it just ain't happening. I've tried all sorts of variations of
> punctuation with no joy. Sometimes, I'm able to get it to print
> out "ARRAY_ONE[2]" and "ARRAY_TWO[2]", but I can't get it to
> print out "baz" or "Carol".
>
> Is it even possible to do what I envision? How? Is there a
> different, better way to do it in Bash? (Keep in mind that I want
> the finished script to be flexible and extensible, hence my
> choice of multiple arrays.)
>
> Any help would be greatly appreciated.
>
> A.
>
> _______________________________________________
> talk mailing list
> talk at nblug.org
> http://nblug.org/cgi-bin/mailman/listinfo/talk




More information about the talk mailing list