Skip to the workspace
Pebellslearn by building
Loops and Functions  ›  Lesson

for Loops: Once per Item

for 12 minA for loop runs its body once for each word in a list, which can come from an array, arguments, a file pattern, a brace range or an arithmetic counter.

shell bash / for Loops: Once per Item

Explore each scene at your own pace.

01 · The rule

The rule

for Loops: Once per Item

A for loop runs its body once for each word in a list, which can come from an array, arguments, a file pattern, a brace range or an arithmetic counter.

Iterate over intact arguments or array elements and inspect each iteration's value.

backup.sh should now make one archive per folder, so a broken photo folder does not spoil the notes backup. Writing the tar line three times would work until someone adds a fourth folder. A for loop runs the same body once for each item, however many there are.

The rule

for name in list; do body; done: the body runs once per word.

for dir in "${dirs[@]}"; do
    name="${dir##*/}"
    tar -czf "$dest/${name// /_}-$stamp.tar.gz" "$dir"
    echo "Packed $dir"
done

On each pass, dir holds the next item, then the body runs. The list can come from many places:

for dir in "${dirs[@]}"; do ...           # an array
for dir in "$@"; do ...                   # the script's arguments
for dir; do ...                           # short for: in "$@"
for f in "$dest"/*.tar.gz; do ...         # files matching a pattern
for n in {1..5}; do ...                   # a brace range: 1 2 3 4 5
for (( i = 0; i < 3; i++ )); do ...       # a counter: 0 1 2

The file pattern form is the safe way to loop over files: each matching name arrives whole, spaces and all. Avoid for f in $(ls): the output of ls is split on spaces, so My Notes.txt becomes two items. One more surprise: if a pattern matches nothing, the loop runs once with the pattern itself, such as the literal text *.log. Guard with [[ -e "$f" ]] || continue.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.