diff --git a/SC2009.md b/SC2009.md index d050873..51818fc 100644 --- a/SC2009.md +++ b/SC2009.md @@ -16,19 +16,24 @@ pgrep -f "$service" > /dev/null 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, ect. +If you want a field that's not the pid, consider doing this through `ps` + `pgrep` instead of `ps` + `grep`: + +``` +for pid in $(pgrep '^python$') +do + user=$(ps -o user= -p "$pid") + echo "The process $pid is run by $user" +done +``` + +This is more robust than `ps .. | grep python | cut ..` because it does not try to match against unrelated fields, such as if the user's name was `pythonguru`. + ### Exceptions -What if you have the pid and you are looking for the matching program name? +You can [[ignore]] this error if you are trying to match against something that `pgrep` doesn't support: -```sh -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? - -```sh -ps ax | grep "$pid" | cut -d" " -f16- +# pgrep does not support filtering by 'nice' value +# shellcheck disable=SC2009 +ps -axo nice=,pid= | grep -v '^ 0' ``` - -Both are valid cases where SC2009 is not valid. -