4

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This method works well for this example. However, if I start the script with set -e (exit on error), then nothing is printed. While obviously not critical, is this indicating that there is an imperfection with this code?
@user3743235 It works with set -e if you start at i=1 and use ((++i)). Why is not clear to me, though.
0

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.

1 Comment

Although this might work for your case, it has several problems that are already pointed out by @codeforester.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.