pgrep
instead of grepping ps
output SH-2009If 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.
pgrep
rolls a number of functionalities into one and can eliminate multiple greps
, cuts
, seds
and awks
.
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
.
ps ax | grep -v grep | grep "$service" > /dev/null
pgrep -f "$service" > /dev/null
You can ignore this issue if you are trying to match against something that pgrep doesn't support.