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:
- Run
ps -ef
to list all processes. - Filter out those lines that contain
java
in theCMD
column. - Filter out those lines that contain
root
in theUID
column. - For each filtered row, get the PID column and run
pargs <PID>
- If
pargs <
PID> output contains a specific stringXYZ
, the issuekill-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.