Using a for loop to loop over multiple arrays in bash
You're iterating over the wrong thing. Your for
saves each element of the array as $i
, not the array's indices. What you want is something like
#!/usr/bin/env bash
a0=(1 2 3 4)
a1=(5 6 7 8)
for ((i=0;i<${#a0[@]};i++))
do
echo ${a0[$i]} ${a1[$i]};
done
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,
grade[John]=100
grade[Paul]=100
grade[George]=90
grade[Ringo]=80
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:
$ declare -A a <-- Create the associative array. $ a[0,0]=1 $ a[0,1]=2 $ a[0,2]=3 $ a[0,3]=4 $ a[1,0]=5 $ a[1,1]=6 $ a[1,2]=7 $ a[1,3]=8 $ for i in 0 1 > do > echo ${a[$i,2]} > done 3 <-- And here’s your output. 7