Reputation: 354
I have two associative arrays as follows
P=([5]=0 [2]=1 [3]=2)
Q=([4]=0 [1]=5 [1]=3)
I have this loop that iterate over each element in P
and each element in Q
to correspond each element in P
with all element in Q
, as follows
for i in ${!P[@]}; do
for j in ${!Q[@]}; do
echo ${P[i]}
echo "-"
echo ${Q[j]}
echo "-----------"
done
done
The expected output would be
1
-
3
-----------
1
-
0
----------- ################# it skips that
1
-
5
----------- #################
2
-
3
-----------
2
-
0
----------- ################# it skips that
2
-
5
----------- #################
0
-
3
-----------
0
-
0
----------- ################# it skips that
0
-
5
----------- #################
but it skips one element from the second array, which is 5
.
Upvotes: 2
Views: 58
Reputation: 85560
Do you realize the typo in the array Q
initialization? You have indexed the array with 1
twice?
Q=([4]=0 [1]=5 [1]=3)
# ^^^ ^^^
As a result, the array would have behaved taking the value at the second indexed entry. So the array expansion "${!Q[@]}"
would have never seen the key that contained the value 5
declare -p Q
declare -A Q=([1]="3" [4]="0" )
Perhaps you want to change your array initialization to
Q=([4]=0 [5]=5 [1]=3)
Also it is weird, you were seeing any output at all with the code you've posted. Because the array printing by indices, should have use the expanded value in the subscript i.e. using "$i"
and "$j"
for i in "${!P[@]}"; do
for j in "${!Q[@]}"; do
echo "${P[$i]}"
echo "-"
echo "${Q[$j]}"
echo "-----------"
done
done
Upvotes: 3