Bash doesn't natively support two-dimensional arrays, but I would like to simulate one. As a minimal working example, suppose that I have two arrays, a0
and a1
:
a0=(1 2 3 4)
a1=(5 6 7 8)
I want to write a for
loop that will print the third element of a0
and a1
. Of course, I could do this manually with two explicit calls to echo
:
echo ${a0[2]}
echo ${a1[2]}
But, I want to generalize this with a for
loop. How can I do this?
I tried the following:
for i in ${a0[@]} ${a1[@]}
do
echo {$i}[2]
echo ${i[2]}
echo ${i}[2]
echo ${$i[2]}
echo ${${i}[2]}
done
But none of those attempts are successful; I get this output:
{1}[2]
1[2]
chgreen.sh: line 30: ${$i[2]}: bad substitution
Do you have any ideas?
Best Answer
As you’ve presumably learned by now from your research, bash doesn’t support multi-dimensional arrays per se, but it does support “associative” arrays. These are basically indexed by a string, rather than a number, so you can have, for example,
As demonstrated (but not explained very well) in the accepted answer of the question you linked to, indices of associative arrays can contain commas, and so a common trick is to concatenate your individual indices (0-1 × 0-3) into a string, separated by commas. While this is more cumbersome than ordinary arrays, it can be effective: