BlueJezza
BlueJezza

Reputation: 63

Kill only processes (instances) of specific Java jar

I need to create automatic script, which kills running processes of specific Java JARs.

I do it manually like this:

jps -v

6753 Jps
4573 myJarToKill.jar
4574 notMyJarToKill.jar
4576 myJarToKill.jar

I pick up specific processes according JAR name for example myJarToKill.jar and run to kill them.

kill 4573 4576  

Is it possible to get numbers of this processes by grep or sth like this? A pass it to kill command?

Upvotes: 6

Views: 3178

Answers (2)

ClaudioM
ClaudioM

Reputation: 1446

The command to use is a combination of grep, awk, and xargs unix command:

jps -v | grep "<your file name>" | grep -v "<if you need to exclude other output>" |awk '{print $<field number>}'|xargs kill -<kill signal>

Before to execute it please read the following explanation:

first of all run this: jps -v | grep "myJarToKill.jar" | awk '{print $1}'

Note: $2 means that the ps output is splitted in space separated field. So when you run the command for the first time please check that awk '{print $2}' output is the expected result otherwise you should change the field number $2 with the ones that you need.

if the "notMyJarToKill.jar" is still present add this:

jps -v  | grep "myJarToKill.jar" | grep -v "notMyJarToKill.jar"| awk '{print $1}' 

Then if the output result contains the pid that you would kill you can run this

jps -v  | grep "myJarToKill.jar" | awk '{print $1}'|xargs kill -9 

Note: you could also use kill -TERM it's depend by your needs.

Regards Claudio

Upvotes: 2

gj13
gj13

Reputation: 1354

kill `jps -v |grep myJarToKill|cut -f1 -d " "`

cut -f1 -d " " is the part, that extract the first "column". The commands in ` get executed and the result is given as a parameter to kill.

Upvotes: 0

Related Questions