freeport: Kill Whatever's Holding Your Port
A small zsh function that finds and kills the process holding a port, in one command.
When a dev server won’t start because the port is already in use, you usually have to look up the PID and kill it by hand. This zsh function does that in one command:
freeport() {
if [[ $# -ne 1 ]]; then
print -u2 "usage: freeport <port>"
return 1
fi
local -a pids
pids=("${(@f)$(lsof -ti ":$1")}")
pids=("${pids[@]:#}")
if (( ${#pids[@]} == 0 )); then
print "No process found on port $1"
return 0
fi
kill "${pids[@]}"
}Usage: freeport 3000.
lsof -ti :3000 finds the PIDs holding the port; the rest just splits the output into an array and kills them. It sends SIGTERM rather than kill -9, so the process gets a chance to shut down cleanly.
It needs lsof, which ships with macOS and most Linux distributions.