Go to content

geek_stuff/server & linux

killport - in bash

I found an command-line utility called `killport` written in rust.

https://github.com/jkfran/killport

  • A command-line tool to easily kill processes running on a specified port.

Features:

  • Kill processes by port number
  • Supports multiple port numbers
  • Verbosity control
  • Works on Linux and macOS

Personally thining, using rust to do this kind of task is just overkill. How many times would this be called and how much performance would it be needed?

 

I think bash is quite enough to get the job done, and maybe append the code to my ~/.bashrc.

 

Here's my quick and dirty code:

killport() {
  if [ $# -ne 0 ]; then
    for port in "$@"; do
      if echo "$port" | grep -Eq '^[0-9]+$'; then
        pids=$(lsof -ti ":$port")
        if [ -n "$pids" ]; then
          echo "Processes listening on port $port: $pids"
          echo "$pids" | xargs kill -9 >/dev/null 2>&1
          echo "Processes listening on port $port have been terminated"
        else
          echo "No process found listening on port $port"
        fi
      else
        echo "Invalid port number: $port"
      fi
    done
  else
    echo "No arguments provided"
  fi
}

 

I haven' tested with macOS, but doubt doesn't work.