I have two for loops:
for i in 0 1 2 3; do echo $i;done
for j in a b c d; do echo $j;done
0
1
2
3
a
b
c
d
I want the output be:
0
a
1
b
2
c
3
d
How to do it?
I have two for loops:
for i in 0 1 2 3; do echo $i;done
for j in a b c d; do echo $j;done
0
1
2
3
a
b
c
d
I want the output be:
0
a
1
b
2
c
3
d
How to do it?
You could define two arrays of the same length with the values you want to iterate over first. Then you can iterate over the indexes of one of the arrays and look them up in both:
Defining arrays works by assigning a list of elements in parentheses, as you see on the first two lines.
The for-loop iterates over
${!arr1[@]}
, which returns a list of all ([@]
) indexes (!
) of the array variablearr1
. This can be used here because we assume that botharr1
andarr2
have exactly the same indexes, because they were defined with the same number of elements. In theory, arrays could have different lengths or even have "holes" i.e. unassigned indexes in between, but both is not the case here, so we don't care for it.Accessing a specific element value of an array at the position defined by the value of the variable
$i
works by typing${arr1[i]}
.Another possibility would be to use an associative array (aka hash aka dictionary) and then iterate over it and retrieving keys and values respectively:
Output: