Hack like a pro: shell `pipe`

By @imil6/29/2017linux

Hi again UNIX shell lovers, as we saw in our last course, a shell command outputs non-errors messages to a special file called stdout, which number is 1 and reads from another special file called stdin which number is 0. Error messages are sent to stderr which number is 2.

To be clear, this means that the following command:

$ ls
. .. foo bar baz

displayed its result to the special file stdout, or 1.
This output can actually be captured by another program by using the | (pipe) symbol. To illustrate its usage, we will use the grep command, which filters the output by matching a pattern. For example, if I would like to output only the lines that contain the word match in a file called myfile.txt, I would do:

$ grep match myfile.txt
beautiful match
matching
those matches

Instead of using a file as the input stream, we could use stdout from a previous command, which the | (pipe) command will transform to grep's stdin!

$ echo 'I like to move it move it'|grep 'move'
I like to move it move it
$ echo 'this phrase won't match'|grep 'not present'

Think of | as a convenient way of filtering big outputs, for example you could very easily see if a directory contains a .jpg file by using |grep '\.jpg'. We won't go deep into grep patterns just yet to keep those courses nice and short :)

In our next shell tip, we will speak about redirections. Stay tuned!

Read more about standard streams in Wikipedia's very well written documentation.

2

comments