all posts

Kill Process Running on a Specfic Port

· 1 min read · unix

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