1

How can I do pgrep -U someUserName using just ps and grep? I.e. not count on pgrep being set in a system?

1

One way:

ps -U someUserName -o pid,comm | awk '/someProcessName/{print $1}'

Note that you might get multiple process ids as output if there are multiple processes running that matches user and process name.

The ps output is really made for readable presentation, not for being processed like this. There are other tools to give more low level access to the process list in a format better suited for scripting, just such as pgrep, Perl/Python/... libraries and so on.


To do it using only ps and grep as you ask for, one could do

ps -U someUserName -o pid,comm | grep 'someProcessName' | grep -oE '^ *([^ ]*)'

This will include leading white space, but that should be a problem in application, e.g.

for i in $(ps -U someUserName -o pid,comm | grep 'someProcessName' | grep -oE '^ *([^ ]*)'); do
    kill $i
done

should work.

But as I said, pkill is a more correct and robust way, and should be widely available.

5
  • awk is a better bet than sed or cut for picking bits out of the output of ps. – Blrfl Mar 30 '12 at 10:43
  • @Blrfl: true, it collapses white space nicely. Will update the answer. – Daniel Andersson Mar 30 '12 at 11:10
  • One could also use awk '/name/{print $1}' directly. – user1686 Mar 30 '12 at 11:14
  • @grawity: also true, one more fix. As a sidenote I didn't really want to use sed or awk to begin with since the poster wanted a platform agnostic solution (on platforms where pgrep and pkill might not be available), and I believe pgrep/pkill are more or less just as widely available as sed/awk (which was the advise on the posters original question). – Daniel Andersson Mar 30 '12 at 11:19
  • awk is specified in POSIX, so odds are good that if you have a system with grep, you'll have it. Same for sed. – Blrfl Mar 30 '12 at 12:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.