Kill Process Running on a Specfic Port

I often have to kill proccesses that weren’t stopped correctly on different ports and can never remember the command.

Snippet

kill -9 $(lsof -ti tcp:4000)

Usage

  1. Replace 4000 in the script above with the port you want to kill the process on.
  2. Run the script in your terminal.

Extending

We can extract this into a function to make it easier to use.

terminate() {
local port=$1
local pid=$(lsof -ti tcp:$port)
if [ -n "$pid" ]; then
kill $pid
echo "Killed process $pid on port $port"
else
echo "No process found on port $port"
fi
}

Then we can use it like this:

terminate 4000
Andrew Mason's profile image

Hey, I'm Andrew 👋

I'm a senior product engineer at Podia, co-host of Remote Ruby and Ruby for All, and co-editor of Ruby Radar. You can explore my writing, learn more about me, or subscribe to my RSS feed.

Page Info

Published:
01 January 2023
Updated:
01 January 2023
Reading Time:
1 min read

Tags