grepping output of ps, exclude the word grep [dupl

2020-02-16 04:37发布

I'm using ps to find the pid of a process created to execute the command "sleep 1234 &" I grep the result to match only "sleep 1234".

ps -A -f | grep "sleep 1234"

however, this matches also the command "grep sleep 1234" itself, returning two lines instead of one. How do I write a pattern for grep to exclude the word 'grep' itself?

Thanks

1条回答
手持菜刀,她持情操
2楼-- · 2020-02-16 05:00

This is a pretty common problem and the easiest solution is to just surround a character in the grep'ed pattern with square brackets:

ps -A -f | grep "[s]leep 1234"

This will now match sleep 1234, but not [s]leep 1234 (because of the literal ] between s and l), and the grep line no longer matches.

The reason that the grep is in the process list is that pipelines are executed from right to left, so the grep is actually executed prior to the ps.

查看更多
登录 后发表回答