Pipes
Connect the output of one command to the input of another.
Basic Usage
#> ls | grep txt
file1.txt
test.txt
#> cat file.txt | grep pattern | sort | uniq
How Pipes Work
command1 | command2 | command3
command1stdout →command2stdincommand2stdout →command3stdincommand3stdout → terminal
Each command runs in its own process.
Exit Code
Pipeline exit code is from the last command:
#> false | true
#> echo $?
0 # From 'true', not 'false'
Common Patterns
Filtering
ls -la | grep txt
ps aux | grep nginx
cat log.txt | grep error
Counting
ls | wc -l # Count files
cat file.txt | wc -l # Count lines
ps aux | grep python | wc -l # Count processes
Text Processing
cat names.txt | sort | uniq
ls -la | awk '{print $5, $9}'
echo hello | tr '[:lower:]' '[:upper:]'
Data Analysis
cat data.csv | cut -d, -f2 | sort | uniq -c | sort -rn | head -10
With Other Features
With Aliases
alias count='wc -l'
ls | count
With Variables
export PATTERN=error
cat log.txt | grep $PATTERN
With Chaining
ls | grep txt && echo "Found txt files"
Difference from ||
| Operator | Purpose |
|---|---|
| | Connect stdout to stdin |
|| | Execute if previous failed |
echo hello | cat # Pipe: passes "hello" to cat
false || echo hello # OR: runs echo because false failed
Troubleshooting
Broken Pipe
If first command produces lots of output but second exits early:
cat huge_file.txt | head -10
# Normal behavior, handled automatically
No Output / Hanging
Command waiting for input:
cat | grep something
# Waiting forever - press Ctrl+C
Limitations
- No
|&(pipe stderr) - No process substitution
<(command)