Simulate pgrep using plain grep

Solution 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.