Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get iteration number within a nested loop

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?

like image 1000
user3743235 Avatar asked Oct 20 '25 01:10

user3743235


1 Answers

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.

like image 197
codeforester Avatar answered Oct 22 '25 20:10

codeforester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!