Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Script to selectively kill processes

Tags:

linux

bash

I'm looking at a way to automate the following:

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

To filter out rows based on specific column values, is there a better way than grep? I can use

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

but then I lose info from all other columns. The closest thing I have right now is:

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

EDIT

I was able to solve the problem by using a 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 reach there. But since I can only accept one answer, I tagged kojiro's answer as the correct one since it helped me a bit more.

like image 226
AweSIM Avatar asked Apr 11 '26 16:04

AweSIM


2 Answers

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 as part of the "proctools" packages for *BSDs and OS X.

like image 95
kojiro Avatar answered Apr 13 '26 05:04

kojiro


You can reduce all grep by using awk:

ps -ef | awk '/[j]ava/ && /root/ {print $1}' | xargs pargs

Searching for pattern /[j]ava/ will skip this awk process from output of ps.

You can also use pkill if it is available on your system.

like image 35
anubhava Avatar answered Apr 13 '26 05:04

anubhava