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

Replace 4000 in the script above with the port you want to kill the process on.

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