[NBLUG/talk] Arrays in Bash
Andrew
argonaut at gmx.co.uk
Fri May 13 06:15:06 PDT 2011
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.
More information about the talk
mailing list