A for loop runs the same body for each word in a list. Accumulators update one step at a time.

Program

Play the script to see n visit three values and total grow.

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

total=0
for n in 2 4 6; do
  total=$((total + n))
done
echo "$total"
  1. total ← 0

    3total=04for n in 2 4 6; do
    values this step0total
  2. n ← 2, loop ← 1/3

    3total=04for n in 2 4 6; do5  total=$((total + n))
    values this step2n1/3loop
  3. total ← 2

    4for n in 2 4 6; do5  total=$((total + n))6done
    values this step0 2total2n
  4. n ← 4, loop ← 2/3

    3total=04for n in 2 4 6; do5  total=$((total + n))
    values this step4n2/3loop
  5. total ← 6

    4for n in 2 4 6; do5  total=$((total + n))6done
    values this step2 6total4n
  6. n ← 6, loop ← 3/3

    3total=04for n in 2 4 6; do5  total=$((total + n))
    values this step6n3/3loop
  7. total ← 12

    4for n in 2 4 6; do5  total=$((total + n))6done
    values this step6 12total6n
  8. echo "$total"

    6done7echo "$total"
    output12
    values this step12total

Add Each Number

  1. total starts at 0.
  2. The loop visits 2, then 4, then 6.
  3. Each pass adds the current n to total.
  4. The script prints 12. | n | Running total | | --- | --- | | 2 | 2 | | 4 | 6 | | 6 | 12 |
for loop `for name in list` assigns one word at a time and runs the body.
accumulator An accumulator stores a running result across loop iterations.

Exercise: for_loop.sh

Use a for loop to add 2, 4, and 6 into a running total and print it