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!

share|improve this question

marked as duplicate by don_crissti, HalosGhost, countermode, Anthony Geoghegan, Sato Katsura Oct 13 '16 at 19:53

This question was marked as an exact duplicate of an existing question.

    
ah thanks! That worked. (point taken, but was having trouble phrasing my question and first handful of search results didn't help) – d4v1dn Oct 13 '16 at 16:42

To answer your first question

#!/bin/bash

A=(ny housing 2010)
B=(ca housing 2010)
C=(fl transportation 2012)


for ((i=0;i<${#A[@]};++i)); do
  if [[ i -eq 0 ]] ; then
    echo "${A[i]}"
    echo "${B[i]}"
    echo "${C[i]}"
 fi
done;

This will print out

ny
ca
fl 

Since I don't know your intention behind this implementation it seems a bit silly to iterate through the array only just to print out the first element of each. You could have also done:

index=0
echo "${A[$index]}"
echo "${B[$index]}"
echo "${C[$index]}"
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.