Search code examples
linuxbashgreppid

Getting User from processid when multiple user processes exist


I'm trying to tweak a bash script to pull back PID's of the individual application accounts when there are multiple applications running as a masterId. This used to run under individual user accounts, but recent changes have forced the applications to all run under a combined "masterId", but still maintain a unique application Id that I can grep against.

Normally

pgrep -u "appId" 

would give me a single PID. Now I have to run:

pgrep -u "masterId"

it returns all of the PID's (each one is it's own application).

1234
2345
3456

I'm trying to come up with a command to bring me back just the PID of the appAccount(n) so I can pipe it into other useful commands. I can do a double grep (which is closer to what I want):

ps aux | grep -i "masterId" | grep -i "appAccount(n)"

and that will get me the entire single process information, but I just want the PID to do something like:

ps aux | grep -i "masterId" | grep -i "appAccount(n)" | xargs sudo -u appAccount(n) kill -9

How do I modify the initial above command to get just the PID? Is there a better way to do this?


Solution

  • pgrep --euid "masterId" --list-full | awk '/appAccount(n)/ {print $1}'
    

    Output the full process command line, then select the one with the desired account and print the first field (pid).