DEV Community

Maroun Maroun
Maroun Maroun

Posted on

A Short Introduction to the Unix Pipes

Simply put, A pipe redirects the output of the left-hand command to the input of the right-hand command. Simple as that. For example, in the following command.

STDIN, STDOUT, STDERR

The Linux creed: "Everything is a file". This includes standard input and output. In Linux, each process gets its own set of files, which gets linked when we invoke piping.

Each process has three default file descriptors:

  • STDIN - /proc/self/fd/0 or /dev/stdin
  • STDOUT - /proc/self/fd/1 or /dev/stdout
  • STDERR - /proc/self/fd/2 or /dev/stderr

The default STDIN is read from your keyboard, while the default for both STDOUT and STDERR is your screen.

Pipes, |, operates on the standard output that's coming from the left side, and the input stream that's expected on its right side.

Having this information, we should be now able to understand how to make a script that's able to process data piped to it:

cat /dev/stdin | grep -oP "\d+" || echo "No digits found"

The output of the cat command will be piped to the input of grep. If it finds a match, it'll print it to the standard output (your screen), otherwise, we'll echo a string indicating that no match was found.

Top comments (0)