From 65ba6f5e84be25191d7d5d9b52178c3aebc1c183 Mon Sep 17 00:00:00 2001 From: cstackpole Date: Tue, 22 Jul 2014 19:40:25 -0700 Subject: [PATCH] Updating to fit the formatting plus adding a few contradictions found from running my own code. --- SC2009.md | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/SC2009.md b/SC2009.md index 95794c3..593e595 100644 --- a/SC2009.md +++ b/SC2009.md @@ -1,12 +1,25 @@ -# SC2009 Consider using pgrep instead of grepping ps output. +## SC2009 Consider using pgrep instead of grepping ps output. -## Problematic Code: +### Problematic Code: -`ps ax | grep -v grep | grep "$service" > /dev/null` + ps ax | grep -v grep | grep "$service" > /dev/null -## Correct Code: +### Correct Code: -`pgrep -f "$service" > /dev/null` + pgrep -f "$service" > /dev/null + +### Rationale: + +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 cat eliminate multiple greps, cuts, seds, awks, ect. + +### Contradictions + +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 SC2009 is not valid. -## Source -This seemed to work for me but I am no expert. \ No newline at end of file