Today's Daily Double is... kill active port processes!
I find that I'm often running into an issue, especially when I have a bunch of agents concurrently attempting changes on a repo, that when I try and spin up the start command (pnpm run dev or whatever it is) in my own terminal window, I eun into issues where a process is already running on this port somewhere. That's fine, it's a very long ago solved issue, and you can look at what ports are running and close them manually. But that's a bit of a pain in the ass as it becomes more and more common and you hardly know if some agent started and never stopped your app in some far distant and ephermeral terminal.
So I've started adding a script into all of my primary workspaces that detects when you have some sort of process already running on the ports that the app needs to use, and if so, it will kill those processes before starting them again in the terminal window where you ran the command. And so I no longer run into the issue of having to track down and manually kill them myself, minor thing but sort of a nice easy to add quality of life improvement.
ex.
in your package.json
"scripts": {
"dev": "bash scripts/dev-with-port-cleanup.sh",
// yadayadayada
}
and at root add file dev-with-port-cleanup.sh
#!/usr/bin/env bash
FALLBACK_CMD="pnpm run build:env-config && vite"
cleanup_and_fallback() {
echo "⚠️ Port cleanup failed, falling back to standard dev command..."
exec bash -c "$FALLBACK_CMD"
}
trap cleanup_and_fallback ERR
command_exists() {
command -v "$1" >/dev/null 2>&1
}
print_warning() {
echo "⚠️ $1"
}
print_info() {
echo "ℹ️ $1"
}
kill_port_processes() {
local port=$1
if command_exists lsof; then
local pids=$(lsof -ti:$port 2>/dev/null || true)
if [[ -n "$pids" ]]; then
print_warning "Found process(es) using port $port, killing them..."
echo "$pids" | xargs kill -9 2>/dev/null || true
sleep 1
fi
else
print_warning "lsof command not found, skipping port cleanup"
fi
}
print_info "Checking for processes on development ports..."
kill_port_processes 5173 || true
print_info "Starting development servers..."
exec bash -c "$FALLBACK_CMD"