8

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?

13

Use pgrep?

pgrep -U xxx yyy

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

2

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 '17 at 8:31
  • What's not easy about this? – GargantuChet Mar 2 '17 at 6:21
  • 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 '17 at 7:59

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.