ps | grep gem
While random readings I came across this gem:
The
Listing 10. Neat grep trickpspipeline also contains a truegrepgem, which was kindly sent to me by Hans Peter Verne. Notice thatgrep -v grepis no longer part of the pipeline; instead, it has been removed andgrep "ssh-agent"has been changed togrep "[s]sh-agent". This singlegrepcommand ends up doing the same thing asgrep ssh-agent | grep -v grep; can you figure out why?Stumped? If you've decided that a
mypids=`ps $psopts 2>/dev/null | grep "[s]sh-agent" | awk '{print $2}'` > /dev/null 2>&1grep "ssh-agent"andgrep "[s]sh-agent"should match the exact same lines of text, you are correct. So why do they generate different results when the output ofpsis piped to them? Here's how it works: when you usegrep "[s]sh-agent", you change how thegrepcommand appears in thepsprocess list. By doing so, you preventgrepfrom matching itself, since the[s]sh-agentstring doesn't match the[s]sh-agentregular expression. Isn't that brilliant? If you still don't get it, play around withgrepa 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