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.
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:
cd ~/project
for fruit in apple banana cherry; do
echo "I like $fruit"
doneI like apple
I like banana
I like cherryThe 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:
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; echo1 2 3 4 5
2 4 6 8 10
1 2 3seq 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:
for ((i = 0; i < 3; i++)); do
echo "round $i"
doneround 0
round 1
round 2Looping 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:
for f in docs/*.txt; do
echo "$f has $(wc -l < "$f") lines"
donedocs/notes.txt has 5 lines
docs/tasks.txt has 5 linesNever 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:
for f in docs/*.txt; do
base="${f%.txt}"
cp "$f" "$base.bak"
done
ls docsnotes.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:
count=3
while [ "$count" -gt 0 ]; do
echo "countdown: $count"
count=$((count - 1))
done
echo "liftoff"countdown: 3
countdown: 2
countdown: 1
liftoffIf 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:
while IFS= read -r line; do
echo "line: $line"
done < docs/tasks.txtline: Buy milk
line: Call the bank
line: Read chapter 3
line: Buy bread
line: Water the plantsSplitting 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:
tail -n +2 data/scores.csv | while IFS=, read -r name team score; do
echo "$name ($team) scored $score"
done | head -n 3Asha (blue) scored 82
Ben (red) scored 67
Chitra (blue) scored 91A 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:
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"
doneodd number: 1
odd number: 3Building 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:
find data docs -type f -print0 | sort -z | while IFS= read -r -d '' f; do
printf "%s: %s lines\n" "$f" "$(wc -l < "$f")"
donedata/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 linesCommon 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.
Ready for the next small win?
Mark the lesson complete when you are ready.