简体   繁体   中英

Get iteration number within a nested loop

For a nested loop that uses two or more arrays, eg

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.

Based on the example given and the method suggested by @codeforester, this is what worked for me (with set -e included near the start of the script).

i=1
for a in ${A[*]}; do
  for b in ${B[*]}; do
    I=$((i++))
    echo "Iteration: $I"
    echo "Combination: $a $b" # show combination of A and B elements
    # task code
  done
done

In this example, array[*] without the double quotes produced the desired result, using each element separately within the loop to produce unique combinations of A and B values, while finding each iteration number within the nested loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM