← All lessons
Processes and scripts · Lesson 6 of 7

Loops

for runs a block once for each word in a list. The list can be written out, come from a wildcard or come from a command.

for duck in mallard teal eider; do
  echo "Hello, $duck"
done

Looping over files with a wildcard is safe even when names have spaces, as long as you quote the variable:

for f in *.jpg; do
  cp "$f" "backup/$f"
done

For numbers, {1..5} gives 1 2 3 4 5, so for i in {1..5} counts. Bash also has the C-style form: for ((i = 0; i < 5; i++)).

while repeats as long as a command succeeds. The usual way to handle a file one line at a time is while read:

while read -r line; do
  echo "Got: $line"
done < names.txt

break leaves a loop early and continue skips to the next round. Don't loop over $(ls) or $(cat file): they split on spaces, so a file called my notes.txt becomes two words. Use a wildcard for files and while read for lines.

Practice

How many times does this print? for x in a b c; do echo $x; done

More info

Quick reference

for x in a b c; do … doneOnce per word.
for f in *.jpgOnce per matching file; quote "$f".
{1..10}The numbers 1 to 10.
while cmd; do … doneRepeat while cmd succeeds.
while read -r line; do … done < fileEach line of a file.
break, continueLeave the loop; next round.

The other Linux courses