This question already has an answer here:
I would like to create a series of arrays, each with 3 parameters, and then loop through each array calling each parameter at different times. I'm having trouble just getting the for loop to output the contents of each array, and I think it is an issue with the syntax of the nested substitutions.
# set 3 arrays with 3 values
A=(ny housing 2010)
B=(ca housing 2010)
C=(fl transportation 2012)
# cycle through 3 arrays echoing value in the first index position
for array in A B C;
do
echo "\${$array[0]}";
done;
With or without the double quotes I get the same output...
# output
${A[0]}
${B[0]}
${C[0]}
Rather than output I am looking for, which should print:
ny
ca
fl
One further step that would be nice to add is to be able to assign each index position to a variable, so that I can call each value by name, e.g. the following...
# set variables to associate with each index position
state=0
dataset=1
year=2
So that....
echo ${A[state]}
echo ${A[year]}
returns
ny
2010
Note that this last part works fine outside of the loop, so hopefully once I get the nested substitutions working, this part will still work fine with everything else
UPDATE
The marked duplicate question was helpful, specifically Gilles solution using 'eval'.
I ultimately wanted to be able to call separate array elements at various times for naming directory paths and existing and new file names. By using 'eval' to first reset new variables (state, data, year) within each iteration of the for loop, I can now call each value by simply using ${state}, ${data}, and ${year}:
for array in A B C;
do
eval "state=\${$array[0]}"
eval "data=\${$array[1]}"
eval "year=\${$array[2]}"
echo "${state}_${data}_${year}"
done;
Thanks for the input!