Anything Else

Tuesday, May 9, 2006

ps | grep gem

While random readings I came across this gem:

The ps pipeline also contains a true grep gem, which was kindly sent to me by Hans Peter Verne. Notice that grep -v grep is no longer part of the pipeline; instead, it has been removed and grep "ssh-agent" has been changed to grep "[s]sh-agent". This single grep command ends up doing the same thing as grep ssh-agent | grep -v grep; can you figure out why?

Listing 10. Neat grep trick

mypids=`ps $psopts 2>/dev/null | grep "[s]sh-agent" | awk '{print $2}'` > /dev/null 2>&1
Stumped? If you've decided that a grep "ssh-agent" and grep "[s]sh-agent" should match the exact same lines of text, you are correct. So why do they generate different results when the output of ps is piped to them? Here's how it works: when you use grep "[s]sh-agent", you change how the grep command appears in the ps process list. By doing so, you prevent grep from matching itself, since the [s]sh-agent string doesn't match the [s]sh-agent regular expression. Isn't that brilliant? If you still don't get it, play around with grep a bit more and you'll get it soon enough.

Label: Tips n Tricks

If you find this post useful, please conside buying me a pizza!

0 Comments

<< Home