For a nested loop that uses two or more arrays, e.g.
A=(0.1 0.2)
B=(2 4 6)
AB=$((${#A[@]}*${#B[@]})) # total number of iterations (length of A * length of B)
for a in ${A[*]}; do
for b in ${B[*]}; do
$(($a+$b)) # task using each combination of A and B
echo ? # show number of the iteration (i.e. 1 to length of AB)
done
done
What is the best way to get the number of the iteration, as shown above using echo
?
You could do this with a simple counter that is incremented inside the inner loop:
i=0
for a in "${A[@]}"; do
for b in "${B[@]}"; do
((i++))
printf "Iteration: $i\n"
: your code
done
done
This would make sense if all the logic is inside the inner-most loop and if we consider the execution of inner-most loop as one iteration.
Note that you need double quotes around array reference to prevent word splitting and globbing. Also, I think you need array[@]
rather than array[*]
as long as you want each element separately and not a concatenated version of all elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With