Pipes and redirection
This is where the terminal becomes magic. The Unix philosophy is: write small programs that do one thing well, and connect them together. Pipes and redirection are the connectors.
Three streams
Every command has three standard streams:
| Stream | Name | Default | Number |
|---|---|---|---|
| stdin | Standard input | Keyboard | 0 |
| stdout | Standard output | Screen | 1 |
| stderr | Standard error (error messages) | Screen | 2 |
Redirection and pipes re-route these streams.
Redirecting output to files: > and >>
| Operator | Does |
|---|---|
cmd > file |
Write stdout to a file, replacing its contents |
cmd >> file |
Append stdout to the end of a file |
cmd < file |
Read stdin from a file |
cmd 2> file |
Write errors to a file |
cmd 2> /dev/null |
Throw errors away (/dev/null is a black hole) |
cmd > out.txt 2>&1 |
Send both output and errors to one file (real bash) |
⚠️
>overwrites without asking. Typing>when you meant>>is a classic way to lose a file's contents.
Pipes: |
A pipe sends the output of one command into the input of the next:
Read it left to right like a factory line:
cat names.txt → sort → uniq → wc -l
(all names) (sorted) (unique) (count them)Each program knows nothing about the others. That's what makes them combinable in endless ways.
Building pipelines step by step
The pro technique: add one stage at a time and check the output each time.
Question: Which name appears most often in names.txt?
uniq -c counts adjacent duplicates, which is why we sort first. sort -rn sorts numerically in reverse, so the biggest count is at the top.
More pipeline examples
Chaining commands: ;, && and ||
These aren't pipes (no data flows between the commands), but they're just as useful:
| Operator | Runs the next command… | Example |
|---|---|---|
a ; b |
Always | cd /tmp ; ls |
a && b |
Only if a succeeded |
mkdir build && cd build |
a || b |
Only if a failed |
cd project || echo "No project folder" |
Every command returns an exit status: 0 = success, anything else = failure. $? holds the last one. Scripts and CI pipelines depend on this.
Practice
- Save a sorted list of every file in
Downloadsto~/downloads-list.txt. - Count how many unique names are in
data/names.txt. - Append today's date to a file called
log.txtthree times, then show it with line numbers. - Write one line that creates a folder
reportsand, only if that works, creates an emptyreports/summary.txtinside it.
1.What's the difference between > and >>?
2.In cat names.txt | sort | uniq -c, why is sort needed?