12

I need the pid for a process given its owner and its command. I can filter a process per user with "ps -u xxx" and its command by "ps -C yyy", but when I try "ps -u xxx -C yyy", they are combined using OR logic. I need AND logic. How can I accomplish this?

1
  • I find this "OR" logic in ps filters is extremely unuseful and counterintuitive (facepalm). Jul 20, 2022 at 6:41

5 Answers 5

17

Use pgrep?

pgrep -U xxx yyy

it returns just the pid (or pids, if more than one process matches).

2
  • @Dave: I cannot reproduce. pgrep systemd shows 9 processes here, pgrep -U mg systemd shows 1, pgrep -a -U mg systemd shows 1. Ubuntu 23.10. Oct 29, 2023 at 15:16
  • I deleted my comment, I was using ps by accident not pgrep sorry for confusion.
    – Dave
    Oct 30, 2023 at 15:28
3

Use grep?

ps -u xxx | grep yyy | grep -v grep
2

You use comm to find PIDs common to both conditions:

ps -u xxx | sort > /tmp/ps-uxxx
ps -C yyy | sort > /tmp/ps-Cyyy
comm -1 -2 /tmp/ps-uxxx /tmp/ps-Cyyy

Using bash, you can use process substitution to avoid the need for temporary files:

comm -1 -2 <(ps -u xxx | sort) <(ps -C yyy | sort)
3
  • Works, thank you very much. ... But is there no easier way (without using pgrep, since this is not available in my context)?
    – guettli
    Feb 28, 2017 at 8:31
  • What's not easy about this? Mar 2, 2017 at 6:21
  • 1
    I know what a comm does. But I use it only once a year. It's not intuitive for me. I guess everyone who uses it daily sees this different. The are good reasons why pgrep exists. Unfortunately pgrep is not available in my context .... But it's solved now. The root of the problem is (according to my point of view), that I need to support the very old operation system without pgrep.
    – guettli
    Mar 2, 2017 at 7:59
0

A subtle refinement to the pgrep approach in the accepted answer (which I also upvoted).

When yyy happens to be a substring of another running command e.g. yyy is gnome-shell, we might get matches for gnome-shell-calendar-service as well. Point being, pgrep is good, but it doesn't completely answer the question (and is the reason I stopped using it).

By comparison, ps -C gnome-shell only returns matches for the gnome-shell process. I also hear @guettli's point about familiarity with commands. Your favorite sed or awk could be committed to muscle memory:

ps -fC gnome-shell | awk '($1=="the_user")'
ps -fC gnome-shell | sed -n '/^the_user\b/p'

If you just want the PID like pgrep, then awk can help:

ps -ouser=,pid= -C gnome-shell | awk '($1=="the_user"){print $2}'

You don't strictly need to replace -f with -o in the ps, but this post is about diminishing returns. If you need precise results, then this is your answer.

0

For the ones who need to achieve it on the fly (no script), here is a bit easier way.

ps -fp $(pgrep -d, -U theUser theCommand)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .