0

Let's say I have three arrays that look like the following:

a=(banana apple grape)
b=(1 2 3)
c=(yellow red purple)

If I wanted to loop through such that each index of each variable is matched, how would I do this? For example, I would want something like the following:

for i in range(0,len(a))
do
    echo "$a[i] $b[i] $c[i]"
done

such that the results would be:

banana 1 yellow
apple 2 red
grape 3 purple
WX_M
  • 458
  • 4
  • 20

1 Answers1

2

The syntax to access array elements is ${array[index]}.

for ((i=0 ; i < ${#a[@]} ; ++i)) ; do
    echo "${a[i]} ${b[i]} ${c[i]}"
done

You can use seq to simulate Python's range:

for i in $(seq 1 ${#a[@]}) ; do 
    echo "${a[i-1]} ${b[i-1]} ${c[i-1]}"
done

where ${#array[@]} returns the size of the array.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • ...while one _can_ use `seq`, I'm not sure there's any compelling respect in which it can be argued to be better than the C-style for syntax used above it. – Charles Duffy Sep 17 '21 at 18:48
  • The fact that you need length-1 was solved in Python by not including the last element in the loop, or in Perl by the distinction between `scalar @array` and `$#array`. In bash, you can use `seq 0 $((${#a[@]}-1))`, but it becomes really hard to read :-) – choroba Sep 17 '21 at 18:52