A Simple Script to Kill Whatever is on a Port
Hey everyone,
If you're a developer, you've almost certainly run into this problem: you stop a development server, but the process doesn't exit cleanly. When you try to restart it, you get the dreaded Address already in use
error because the old process is still squatting on the port.
The usual solution is a multi-step dance of using lsof
or netstat
to find the Process ID (PID) and then using kill
to terminate it. It's a hassle. To solve this, I wrote a simple shell script that automates the whole process into a single command.
The kill-port
Script
This script does exactly one thing: it finds and kills the process running on a given port. It's designed to be both fast and widely compatible.
GitHub Gist: kill-port.sh
#!/bin/bash
find_pids() {
local port=$1
if command -v ss &>/dev/null; then
ss -lptn "sport = :$port" 2>/dev/null \
| grep -oP 'pid=\K[0-9]+' \
| sort -u # one PID per line
elif command -v lsof &>/dev/null; then
lsof -t -i:"$port"
else
echo "Neither ss nor lsof found." >&2
return 1
fi
}
#— main —#
[ -z "$1" ] && { echo "Usage: $0 <port>"; exit 1; }
PORT=$1
# Get PIDs as a space-separated list
PIDS=$(find_pids "$PORT" | tr '\n' ' ')
if [ -n "$PIDS" ]; then
echo "Killing processes on port $PORT: $PIDS"
# shellcheck disable=SC2086 # intentional word-splitting so each PID is separate
kill -9 $PIDS
echo "Process(es) killed."
else
echo "No process found on port $PORT"
fi
How It Works
The script is designed to be efficient. It first checks if the modern ss
(socket statistics) command is available, which is very fast for this kind of task. If ss
isn't found, it gracefully falls back to using the more traditional lsof
command, ensuring it works in a wide variety of environments.
This approach makes the script fast on modern Linux systems while remaining compatible with older ones. Once it finds the PID using either method, it uses kill -9
to terminate the process.
How to Use It
- Save the code above to a file named
kill-port
in a directory that's in yourPATH
(like~/.local/bin
). - Make the script executable:
chmod +x ~/.local/bin/kill-port
- Now, anytime a process is stuck on a port, you can just run:
kill-port 5000
It's a tiny utility, but it's one of those quality-of-life scripts that saves a little bit of time and a whole lot of annoyance.
As always,
Michael Garcia a.k.a. TheCrazyGM
You are always making my quality of life go up! Great work today, and thanks for dusting off this script for the Project Builder!
!PAKX
!PIMP
!PIZZA
View or trade
PAKX
tokens.Use !PAKX command if you hold enough balance to call for a @pakx vote on worthy posts! More details available on PAKX Blog.
$PIZZA slices delivered:
@ecoinstant(1/20) tipped @thecrazygm
Come get MOONed!
This is another super useful tool! While I haven't experienced it in a developmental environment, I have dealt with this issue with various applications, most notably my Qortal node. I love your coding creativity! 😁 🙏 💚 ✨ 🤙