Pipe (Combine Commands)
Pipe is used to combine two or more commands. Outputs of the first command become inputs of the second command.
Difference between redirection and pipe
Redirection is used mostly to connect a command with a file while the pipe is used to connect commands as shown in the illustration below.
Pipe syntax
Using pipes is simple – you just need to connect two commands with the pipe symbol " |
".
To demonstrate how the pipe works with a simple example, combine the ls
command and the grep
command to display a list of directories under / (root) that contain a certain character in their name.
First, run the ls
command without the pipe to see the difference.
ls /
bin dev home lib32 libx32 media opt root sbin srv tmp var
boot etc lib lib64 lost+found mnt proc run snap sys usr
Then, run the ls
command while piping the grep
command to list only the directories with r in their name.
ls / | grep r
You'll see a result like the one below.
proc
root
run
srv
usr
var
Connecting more than two commands
You can connect more than two commands with pipes.
For example, you can reverse the order of the output in the previous example.
ls / | grep r | sort -r
var
usr
srv
run
root
proc