Course outline · 0% complete

0/29 lessons0%

Course overview →

for loops

lesson 9-1 · ~11 min · 24/29

Quiz

Warm-up from lesson 8-2: your script is called as ./tag.sh a.txt b.txt c.txt. Which variable holds ALL the arguments at once?

Do it once per item

Loops are where the terminal starts beating any amount of clicking: convert 200 images, create a directory per chapter, check every log file — each is one loop, written in seconds.

A for loop repeats a block of commands once for each item in a list:

for fruit in apple banana cherry; do
  echo "I packed: $fruit"
done

Anatomy: for VARIABLE in LIST; do COMMANDS; done. Each round, the variable takes the next value from the list.

The list can come from anywhere, and that's the power move: a wildcard from lesson 4-2 (for f in *.txt), the script's arguments (for arg in "$@"), or numbers (for n in 1 2 3).

for fruit in apple banana cherryapplebananacherry$fruit
Each pass of the loop, $fruit points at the next item until the list runs out.

Code exercise · bash

Run both loops: one over words, one over a *.txt wildcard (note how three.md is skipped).

Number and letter ranges: brace expansion

Typing 1 2 3 4 5 by hand doesn't scale. Brace expansion generates the list for you: before running the command, bash rewrites {1..5} into 1 2 3 4 5 (and {a..c} into a b c). Like the wildcards in lesson 4-2, this is the shell expanding text before the command runs — the loop never sees braces, only the finished list.

It works outside loops too: mkdir chapter{1..9} creates nine directories in one command, and cp app.conf{,.bak} expands to cp app.conf app.conf.bak — a beloved backup idiom.

Code exercise · bash

Run it: two loops driven by brace ranges, one numeric and one alphabetic.

Quiz

How many times does this run? for x in *.log; do echo hi; done, in a directory with 4 .log files and 2 .txt files

Code exercise · bash

Your turn: a countdown. Loop over 5 4 3 2 1 printing `T-minus N` each time, then print `liftoff` after the loop. Expected output: ``` T-minus 5 T-minus 4 T-minus 3 T-minus 2 T-minus 1 liftoff ```