Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find processes based on port and kill them all? [duplicate]

Tags:

bash

shell

Find processes based on port number and kill them all.

ps -efl | grep PORT_NUMBER | kill -9 process_found_previously 

how to complete the last column?

like image 703
yli Avatar asked Feb 18 '11 16:02

yli


1 Answers

The problem with ps -efl | grep PORT_NUMBER is that PORT_NUMBER may match other columns in the output of ps as well (date, time, pid, ...). A potential killing spree if run by root!

I would do this instead :

PORT_NUMBER=1234 lsof -i tcp:${PORT_NUMBER} | awk 'NR!=1 {print $2}' | xargs kill  

Breakdown of command

  • (lsof -i tcp:${PORT_NUMBER}) -- list all processes that is listening on that tcp port
  • (awk 'NR!=1 {print $2}') -- ignore first line, print second column of each line
  • (xargs kill) -- pass on the results as an argument to kill. There may be several.
like image 171
Shawn Chin Avatar answered Sep 24 '22 00:09

Shawn Chin