Linux scripts that selectively terminate processes

Linux scripts that selectively terminate processes … here is a solution to the problem.

Linux scripts that selectively terminate processes

I’m looking for a way to automate the following:

  1. Run ps -ef to list all processes.
  2. Filter out those lines that contain java in the CMD column.
  3. Filter out those lines that contain root in the UID column.
  4. For each filtered row, get the PID column and run pargs <PID>
  5. If pargs <PID> output contains a specific string XYZ, the issue kill-9 <PID> command.

Is there a better way to filter out rows based on specific column values than grep? ? I can use

ps -ef | awk '{print $1}' | grep <UID>

But then I lost information for all the other columns. The closest I have now is:

ps -ef | grep java | grep root | grep -v grep | xargs pargs | ?????

Edit

I was able to solve the problem by using the following script:

ps -ef | awk '/[j]ava/ && /root/ {print $2}' | while read PID; do
    pargs "$PID" | grep "Args" > /dev/null && kill -9 $PID && echo "$PID : Java process killed!"
done

Both Anubhava's and Kojiro's answers helped me get there. But because I can only accept one answer, I marked kojiro's answer as correct because it helped me more.

Solution

Consider pgrep:

pgrep -U 0 java | while read pid; do
    pargs "$pid" | grep -qF XYZ && kill "$pid"
done

pgrep and pkill are available on many Linux systems and are part of the “proctools” package for *BSD and OS X.

Related Problems and Solutions