Chapter 5. Redirection, Pipe and Shell Script

Pipe (Combine Commands)

Pipe (Combine Commands)
Tag:

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-Combine-Commands

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.

Command Line - INPUT
ls /
Command Line - RESPONSE
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.

Command Line - INPUT
ls / | grep r

You'll see a result like the one below.

Command Line - RESPONSE
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.

Command Line - INPUT
ls / | grep r | sort -r
Command Line - RESPONSE
var
usr
srv
run
root
proc

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-Combine-Commands

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.

Command Line - INPUT
ls /
Command Line - RESPONSE
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.

Command Line - INPUT
ls / | grep r

You'll see a result like the one below.

Command Line - RESPONSE
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.

Command Line - INPUT
ls / | grep r | sort -r
Command Line - RESPONSE
var
usr
srv
run
root
proc
Tag: