Loops and Lists
For Loops
Accumulating Values
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"
total ← 0
3total=04for n in 2 4 6; dovalues this step0totaln ← 2, loop ← 1/3
3total=04for n in 2 4 6; do5 total=$((total + n))values this step2n1/3looptotal ← 2
4for n in 2 4 6; do5 total=$((total + n))6donevalues this step0 → 2total2nn ← 4, loop ← 2/3
3total=04for n in 2 4 6; do5 total=$((total + n))values this step4n2/3looptotal ← 6
4for n in 2 4 6; do5 total=$((total + n))6donevalues this step2 → 6total4nn ← 6, loop ← 3/3
3total=04for n in 2 4 6; do5 total=$((total + n))values this step6n3/3looptotal ← 12
4for n in 2 4 6; do5 total=$((total + n))6donevalues this step6 → 12total6necho "$total"
6done7echo "$total"output12values this step12total
Add Each Number
totalstarts at0.- The loop visits
2, then4, then6. - Each pass adds the current
ntototal. - 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