Hack like a pro: shell `pipe`

in linux •  7 years ago 

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.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Congratulations @imil! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of posts published

Click on any badge to view your own Board of Honnor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

  ·  7 years ago (edited)

Very cool. I'm always using grep to search recursively: grep -r 'something' somedirectory so thanks for the reminder you can use it on a single file.

I also like to use it to filter results of find:

ls -l | grep '2017'

Would be files from this year in the current directory.

Following you.

  ·  7 years ago (edited)

Thanks @mikeill, I'll eventually get to more difficult scenarios, my first target here are less fluent linux/unix users, I'd like to make them love the CLI ;) but comments from more educated users are really welcome too! Following you back

Sweet. See you around.