Introduction
Pipe in Linux (or Unix) passes the output of one command as input to another command. The pipe is represented by the | (vertical bar) symbol.
Prerequisites
What is the use case of pipe in Linux?
Linux commands are atomic commands. It means they serve one and only one responsibility. It is the best example of SRP(Single Responsibility Principle).
So to achieve complex tasks we need to combine these commands (pass the output of one command as input to another command). This is achieved through the pipe.
Syntax
command1 | command2 | command3
# Pipe can chain (connect) any number of commands.
How to use the pipe(|)?
The use of pipe(|) depends on the need of the problem.
Let us understand this with an example.
Problem 1 – Check if the ssh process is running or not.
Answer 1 – ps aux | grep ssh
Problem 2 – Count the files matching with “user” in /var/log Directory.
Answer – ls /var/log | grep “*user.*” | wc -l
Now you can understand the role of pipe in Linux in building complex commands and how easy it is to use.
Top use cases of Pipe(|)
Check if a process is running or not.
Solution – ps aux | grep process_name
`
The example is already provided above.
Count the total occurrence of a phrase in all the files in a given directory.
Solution – grep -r "phrase" /path/to/directory | wc -l
Conclusion
In this post, you learned about pipe in Linux, what its function is, how to use it, and top use cases of pipe in Linux.
Enjoy the Post!
4 thoughts on “Pipe in Linux (or Unix): A Master Guide in 5 Minutes With An Easy Approach”