Introduction to Pipes
This is where Linux gets its power: connecting commands.
The Pipe Operator: |
The pipe | sends stdout of one command to stdin of another:
lsoutputs filenames|pipes that outputwc -lcounts lines
Result: number of files.
Building Pipelines
Read this left to right:
cat access.log- read the filegrep 'ERROR'- filter for error lineswc -l- count them
47 errors in the log.
Why Pipes Are Powerful
Without pipes, you'd need temp files:
# Without pipes (ugly)
cat access.log > temp1.txt
grep 'ERROR' temp1.txt > temp2.txt
wc -l temp2.txt
rm temp1.txt temp2.txt
# With pipes (beautiful)
cat access.log | grep 'ERROR' | wc -l
Pipes are cleaner and faster - data flows through memory, not disk.
Unix Philosophy
"Do one thing well" - Unix tools are designed to be small and focused. Pipes combine them into powerful workflows. This is the Unix philosophy in action.
Common Pipe Patterns
Filter and Count
Sort and Unique
Find and Process
Filter and Format
Multiple Pipes
Chain as many as you need:
This finds the top 5 most common error timestamps.
Stderr and Pipes
Important: pipes only transfer stdout. Stderr still goes to the terminal.
The error appears, but wc receives nothing (empty stdin).
To pipe stderr too:
Head and Tail in Pipes
Less for Long Output
Perfect when you need to explore output interactively.
Advanced: Process Substitution
Sometimes you need to pass command output where a filename is expected:
# Compare output of two commands
diff <(ls dir1) <(ls dir2)
# Read from command output
while read line; do
echo "$line"
done < <(cat file.txt)
<(command) creates a temporary file-like object from command output. It's like a pipe, but works where filenames are required.
When to Use Process Substitution
Use it when a command requires a filename, not stdin. For example, diff expects two files - process substitution lets you compare command outputs directly.
What does `cat file.txt | grep 'error' | wc -l` do?
Key Takeaways
|connects stdout of one command to stdin of another- Build complex workflows from simple commands
- Read pipelines left to right
- Pipes only transfer stdout (use
2>&1for stderr) - This is the Unix philosophy: small tools, combined creatively
Next: building complex pipelines with multiple commands.