Bash Pipes
What is a Pipe?
A pipe (|) sends the output of one command directly into the next command.
This lets you combine small, simple commands to do bigger jobs. It is one of the most useful features of Bash.
All examples below use this file, fruits.txt:
apple
banana
apple
cherry
banana
apple
Your First Pipe
Here, cat prints the file, and the pipe sends that output to head -n 2, which keeps the first two lines:
Chain Several Commands
You can connect as many commands as you like. Each one works on the output of the one before it.
This sorts the fruits, then uniq removes the duplicate lines:
Add -c to uniq to count each line, then sort by that count, highest first:
Example: Count and Rank
sort fruits.txt | uniq -c | sort -rn
3 apple
2 banana
1 cherry
Count Results with a Pipe
Piping into wc -l counts the lines of any output. This counts how many lines contain "apple":
Save and Show at the Same Time (tee)
The tee command writes its input to a file and passes it on to the screen (or the next command):
Example: Use tee in a Pipe
sort fruits.txt | uniq | tee unique.txt
apple
banana
cherry
cat unique.txt
apple
banana
cherry
Pipes vs. Redirection
A pipe (|) connects a command to another command.
Redirection (>) connects a command to a file. See Bash Redirection.