Pipe (|) in Linux
What is a pipe?
In Unix/Linux, a pipe (|) is used to connect the output of one command to the input of another.
It allows command chaining, enabling small programs to work together efficiently — a core concept of the Unix philosophy.
Syntax
command1 | command2command1: produces output (stdout)command2: reads input (stdin) fromcommand1’s output
Common Examples
View log and filter
cat /var/log/syslog | grep "error"cat: displays the loggrep: filters lines containing “error”
Count files
ls -1 | wc -lls -1: lists one file per linewc -l: counts number of lines (i.e., files)
Sort and remove duplicates
cat file.txt | sort | uniqsort: sorts linesuniq: removes consecutive duplicates
Chain multiple commands
ps aux | grep apache | awk '{print $2}' | xargs kill- Lists processes
- Filters those with “apache”
- Extracts PID
- Kills the processes
Best Practices
-
Avoid using
catunnecessarily. Example:grep "error" file.txt # better than cat file.txt | grep "error" -
Pipes can be chained for multiple processing steps.
-
Combine with redirection for logging output:
command1 | command2 > output.txt
Why use pipes?
- Save time and typing
- Avoid temporary files
- Let small tools do one job each and work together
- Powerful for automation and scripting
Last updated on