Piping in unix-like operating systems

Piping in unix-like operating systems

Prerequisites

  • redirection

Piping is a very useful feature in bash. You can connect the standard output of a command to be the standard input of another command.

The first type of pipe is like this. A one to one pipe. stdout of 1st command goes as stdin of the 2nd command.

Image description

ls -hl | wc -l

The pipe character or operator is the | character. In the previous command, we long listed ls -l the contents of the current working directory in a human readable format -h. Then, we passed the output of that command (instead of getting printed to the terminal) as an input or standard input (stdin) to the second command wc and -l option counts the lines of the list only. So the output of the whole command ls -hl | wc -l is the number of objects (files, directories, etc) located in the current working directory (cwd).

Image description

The second way to pipe commands is like this. That way you can redirect the output of the 1st command to a file and to a 2nd command.

ls -hl | tee output.txt | wc -l

The tee command is what allows us to do this. It takes the stdout of the first command saves the output to a file and passes it to the wc command.