Lesson 11.4: Loops: for, while and until
Repeating work with for over a list, a brace range and a wildcard; counting errors in every log with a for loop in a script; reading a file line by line with while read; counting down with while and retrying with until; skipping and stopping with continue and break; the C-style for (( )); renaming many files at once with ${f%.log}; and writing your own loop script in nano.
19 min
You will learn to
- Loop over words, ranges and files with for
- Read a file line by line with while read
- Use while and until with a condition
- Skip an item with continue and stop with break
- Write a C-style for (( ))
- Rename many files safely in a loop
Key terms
- Loop
- A block of commands that runs again and again: once per item (for) or as long as a condition holds (while, until).
- Iteration
- One pass through the loop body.
- for … in … do … done
- Runs the body once for each word in a list; the loop variable holds the current word.
- while / until
- while repeats while a command succeeds; until repeats until it succeeds.
- break / continue
- break leaves the loop at once; continue jumps to the next iteration.
- Infinite loop
- A loop whose condition never becomes false. Stop it with Ctrl+C.
← Making decisions: if, test and case · All lessons · Functions and a real backup script →