Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a process with a certain value in the command lying between a specific range

Tags:

linux

command

awk

I run a lot of curl process through a script. These curl processes specify the local ports to be used. Now I need to kill some of these processes based on their local ports. For eg i want to kill the processes with the local ports lying between 30000 and 30100.

enter image description here

Now how do i kill only the processes with local ports between 30000 and 30100.

I believe i can write a perl script to parse the output and extract the values of the local port then kill the process satifying my conditions, but is there a way to do it with a single nested linux command, perhaps using awk?

like image 415
Rishabh Avatar asked Jun 06 '26 16:06

Rishabh


2 Answers

You can do:

ps -aux | awk '$14>=30000 && $14<=30100 && $0~/curl/ { print $2 }' | xargs kill -9

Based on your screenshot, port values appear on 14th column ($14 holds this value), putting a check of $0~/curl/ grabs only those lines with curl effectively removing the need for grep. print $2 prints the process id. We then pipe the output to xargs and kill.

like image 153
jaypal singh Avatar answered Jun 08 '26 06:06

jaypal singh


You can use

kill  `lsof -i TCP@<your-ip-address>:30000-30100 -t`

to kill the processes attached to those ports, where <your-ip-address> must be the IP address that those connections use on the local side (this could be "localhost" or the external IP address of your host, depending).

If you leave the IP address out, you risk killing unrelated processes (that are connected to a destination port in the given range).

See this post for the background on lsof.

like image 25
KeepCalmAndCarryOn Avatar answered Jun 08 '26 06:06

KeepCalmAndCarryOn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!