Skip to content

Files

Latest commit

 

History

History
39 lines (24 loc) · 949 Bytes

SC2009.md

File metadata and controls

39 lines (24 loc) · 949 Bytes

Pattern: Grepping ps output instead of using pgrep

Issue: -

Description

If you are just after a pid from a running program, then pgrep is a much safer alternative. Especially if you are also looking for a pid belonging to a certain user or group. All of the parameters are in one command and it can eliminate multiple greps, cuts, seds, awks, etc.

Example of incorrect code:

ps ax | grep -v grep | grep "$service" > /dev/null

Example of correct code:

pgrep -f "$service" > /dev/null

Exceptions

What if you have the pid and you are looking for the matching program name?

pid=123; ps ax | grep "$pid"

What if you want a range of the ps field, like from the 16th space to the end of the line?

ps ax | grep "$pid" | cut -d" " -f16-

Both are valid cases where this rule is not valid.

Further Reading