Skip to lesson

Linux Command Line · Lesson 39 of 43

Loops: for, while and reading files

Repeat commands with for and while loops in Bash: loop over lists, files and number ranges, read files line by line, and use break and continue.

Beginner to intermediate·14 min·Shell scripting·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will repeat work without copying commands: rename a hundred files, check a list of servers, process every line of a data file. Loops are what make scripts save real time.

for: one round per item

A for loop assigns each word of a list to a variable in turn and runs the body once for each:

bash
cd ~/project
for fruit in apple banana cherry; do
  echo "I like $fruit"
done
result
I like apple
I like banana
I like cherry

The do and done keywords wrap the body. On one line, separate the parts with semicolons: for f in a b c; do echo "$f"; done.

Looping over ranges

Brace expansion and seq generate numbers. Braces are built into Bash and seq also accepts variables:

bash
for n in {1..5}; do printf "%s " "$n"; done; echo
for n in $(seq 2 2 10); do printf "%s " "$n"; done; echo
max=3
for n in $(seq 1 $max); do printf "%s " "$n"; done; echo
result
1 2 3 4 5 
2 4 6 8 10 
1 2 3

seq START STEP END counts, and with two arguments the step is 1. Braces do not accept variables inside the range, so use seq for those cases. Bash also has a C-style loop for counting:

bash
for ((i = 0; i < 3; i++)); do
  echo "round $i"
done
result
round 0
round 1
round 2

Looping over files

To process files, give the loop a glob, a pattern the shell expands to the matching names. Each name arrives as one word, even if it contains spaces:

bash
for f in docs/*.txt; do
  echo "$f has $(wc -l < "$f") lines"
done
result
docs/notes.txt has 5 lines
docs/tasks.txt has 5 lines

Never loop over $(ls). The output of ls is split at spaces, so a file called my notes.txt would turn into two items. Globs do the right thing. If a glob matches nothing, Bash passes the pattern through literally, so check inside the loop with [ -e "$f" ] || continue.

Here is a practical example: give every .txt file in docs a backup copy with a changed name, using parameter expansion to cut the extension off:

bash
for f in docs/*.txt; do
  base="${f%.txt}"
  cp "$f" "$base.bak"
done
ls docs
result
notes.bak
notes.txt
tasks.bak
tasks.txt

${f%.txt} removes the shortest match of .txt from the end of the value. Other handy forms are ${f##*/} (the part after the last slash, like basename) and ${f%/*} (the part before it, like dirname).

while: repeat while a condition holds

A while loop runs the body as long as its condition command succeeds:

bash
count=3
while [ "$count" -gt 0 ]; do
  echo "countdown: $count"
  count=$((count - 1))
done
echo "liftoff"
result
countdown: 3
countdown: 2
countdown: 1
liftoff

If the condition never fails, the loop never ends. Press Ctrl+C to stop a runaway loop in a terminal. until is the opposite of while: it repeats while the condition fails.

Reading a file line by line

The standard pattern pairs while read with a redirect at the end of the loop. IFS= keeps leading spaces and -r keeps backslashes:

bash
while IFS= read -r line; do
  echo "line: $line"
done < docs/tasks.txt
result
line: Buy milk
line: Call the bank
line: Read chapter 3
line: Buy bread
line: Water the plants

Splitting a line into fields works through IFS, the input field separator. This reads the scores table, skips the header, and prints a sentence for each person:

bash
tail -n +2 data/scores.csv | while IFS=, read -r name team score; do
  echo "$name ($team) scored $score"
done | head -n 3
result
Asha (blue) scored 82
Ben (red) scored 67
Chitra (blue) scored 91

A pipe starts the loop in a subshell, so variables set inside it vanish after the loop. To keep them, feed the loop with a redirect or process substitution, done < <(command).

break and continue

break leaves the loop at once, and continue skips to the next round:

bash
for n in 1 2 3 4 5 6; do
  if [ $((n % 2)) -eq 0 ]; then continue; fi
  if [ "$n" -gt 4 ]; then break; fi
  echo "odd number: $n"
done
result
odd number: 1
odd number: 3

Building a menu of work

Loops combine nicely with the earlier lessons. This script counts the lines of every file in a folder tree, using find and a safe while read loop with null separators that handle every legal file name:

bash
find data docs -type f -print0 | sort -z | while IFS= read -r -d '' f; do
  printf "%s: %s lines\n" "$f" "$(wc -l < "$f")"
done
result
data/fruit.txt: 7 lines
data/scores.csv: 7 lines
docs/notes.bak: 5 lines
docs/notes.txt: 5 lines
docs/tasks.bak: 5 lines
docs/tasks.txt: 5 lines

Common mistakes

Looping over $(ls). It breaks on spaces. Use a glob or find -print0.

Forgetting quotes around "$f". A name with a space becomes two arguments.

Expecting variables from a piped loop to survive. A pipe creates a subshell.

An infinite loop. Make sure the condition can become false, and know Ctrl+C.

Using {1..$n}. Braces do not expand variables. Use seq 1 "$n".

Exercise

Write a loop that prints the squares of the numbers 1 to 5. Loop over the .csv and .log files in ~/project and print the size of each with wc -c. Then read data/fruit.txt line by line and print only the lines that are not apple, numbering each output line with a counter variable.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 Which loop processes every .txt file in the current folder safely?
02 What does while read -r line; do ...; done < file do?
03 What does continue do inside a loop?
04 What does echo {1..3} print?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Tools and Workflow

Linux Command Line tutorial

Learn to work confidently in the terminal, from your first command to pipes, permissions, scripts and a real log-analysis project.

Your progress 0/43
Learning something new?Explore all courses