🎓 A1Learner
🔍
0 of 50 lessons completed

Shell For Loops

A for loop is a way to repeat commands once for each word in a list. It puts each word in turn into a variable, and runs the block with that value.

Loop over numbers

The block runs once for each number.

for n in 1 2 3; do
  echo "Number $n"
done

Loop over text files

The glob expands to the text files first.

for f in *.txt; do
  echo "File: $f"
done

Loop over pictures

The block runs once for each picture.

for pic in photos/*.jpg; do
  echo "$pic"
done

Loop over a brace range

A brace range makes the list of numbers.

for d in {1..3}; do
  echo "Day $d"
done

Example

for f in docs/*.txt; do
  echo "--- $f"
  cat "$f"
done

Key points

  • For loop: for name in words runs the block once for each word.
  • Use a glob as the list to loop over matching files.
  • Use a brace range as the list to loop over numbers.
  • Loop variable: the variable holds the current word while the block runs.

In this example, the glob expands to the two text files in docs. The loop runs once for each file. Each run prints the file name and then the file.

Note

Quote "$name" inside the loop when a file name may hold spaces.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does for f in *.txt do?