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
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

...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.
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 :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.