Advanced

Loops and conditionals

The shell has loops and tests, and they read differently from a programming language because they operate on words and exit statuses. Once that is clear, a shell loop is a short way to do the same thing across a list of files.

What you will see

one.txt 2 and two.txt 3 - the < redirect feeds wc without adding the filename to its output.

About 1 min of reading

Try It

Loop over files and count lines.

1

Set up

printf 'a\nb\n' > one.txt && printf 'a\nb\nc\n' > two.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Two files with 2 and 3 lines.
2

Loop

for f in *.txt; do printf '%s %s\n' "$f" "$(wc -l < "$f")"; done

Before you run it, say out loud what it will print. Then open the answer.

What it prints
one.txt 2 and two.txt 3 - the < redirect feeds wc without adding the filename to its output.

Data Flow

A list drives a repeated command.
1 Expand the list once
↓
2 Bind each item to a name
↓
3 Run the body with it quoted
↓
4 Collect the output
Why this works
Prefer a pipeline to a loop

A loop that runs one command per file is often one command with a list. grep over a glob or xargs does the work in one process, and the loop version is slower and harder to read.

Loop variables are global

A shell loop leaves its variable set after it finishes, which bites when the same name is reused later. Use a name that says what it holds, and the leftover value stops being a mystery.

Examples

for over a list

for f in *.txt; do wc -l "$f"; done. The glob expands once, then the body runs per name. Quoting inside the loop is what keeps names with spaces working.

if tests an exit status

if command; then ... runs the command and branches on whether it succeeded. Test brackets are a program that returns a status. Both are the same mechanism: success is zero, failure is not.

while read for lines

while read -r line; do ... done < file processes a file line by line. The -r flag stops backslashes being eaten, which is a default worth setting without thinking.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Finding files by rule
Previous Lesson
Finding files by rule
Next Lesson
Exit status and failure
Exit status and failure →