Performance work starts by bounding how much work a loop can do. A clear limit keeps a script from processing more rows than the caller intended.

Program

Play the script to choose the loop limit and see how many items are processed.

limit
loop_bound_plan.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

limit=3
count=0
for i in 1 2 3 4 5; do
    if [[ "$i" -gt "$limit" ]]; then
        break
    fi
    count=$((count + 1))
done
echo "processed=$count limit=$limit"
#!/usr/bin/env bash

limit=5
count=0
for i in 1 2 3 4 5; do
    if [[ "$i" -gt "$limit" ]]; then
        break
    fi
    count=$((count + 1))
done
echo "processed=$count limit=$limit"
  1. limit ← 3

    3limit=34count=0
    values this step3limit
  2. count ← 0

    3limit=34count=05for i in 1 2 3 4 5; do
    values this step0count
  3. count ← 1

    8    fi9    count=$((count + 1))10done
    values this step0 1count1i
  4. count ← 2

    8    fi9    count=$((count + 1))10done
    values this step1 2count2i
  5. count ← 3

    8    fi9    count=$((count + 1))10done
    values this step2 3count3i
  6. if [[ "$i" -gt "$limit" ]]; then

    5for i in 1 2 3 4 5; do6    if [[ "$i" -gt "$limit" ]]; then7        break
    values this step4i3limit3count
  7. echo "processed=$count limit=$limit"

    10done11echo "processed=$count limit=$limit"
    outputprocessed=3 limit=3
    values this step3count3limit
  1. limit ← 5

    3limit=54count=0
    values this step5limit
  2. count ← 0

    3limit=54count=05for i in 1 2 3 4 5; do
    values this step0count
  3. count ← 1

    8    fi9    count=$((count + 1))10done
    values this step0 1count1i
  4. count ← 2

    8    fi9    count=$((count + 1))10done
    values this step1 2count2i
  5. count ← 3

    8    fi9    count=$((count + 1))10done
    values this step2 3count3i
  6. count ← 4

    8    fi9    count=$((count + 1))10done
    values this step3 4count4i
  7. count ← 5

    8    fi9    count=$((count + 1))10done
    values this step4 5count5i
  8. echo "processed=$count limit=$limit"

    10done11echo "processed=$count limit=$limit"
    outputprocessed=5 limit=5
    values this step5count5limit
loop bound A loop bound limits how many iterations a script can perform.
early stop `break` exits the loop once the boundary is reached.
work count Counting processed items makes the boundary visible in output.