Created
May 29, 2026 11:55
-
-
Save jwahdatehagh/f0357d53c1780aa2e0f5ffe6e81ac933 to your computer and use it in GitHub Desktop.
killport — kill whatever is listening on a TCP port (LISTEN sockets only, so clients connected to the port are left alone)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # killport <port> [signal] | |
| # Kill whatever is *listening* on a TCP port (not clients merely connected to it). | |
| set -euo pipefail | |
| port="${1:-}" | |
| signal="${2:-TERM}" | |
| if [[ -z "$port" || ! "$port" =~ ^[0-9]+$ ]]; then | |
| echo "usage: killport <port> [signal]" >&2 | |
| exit 1 | |
| fi | |
| # Only listening sockets — avoids killing clients with an established connection. | |
| pids="$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null || true)" | |
| if [[ -z "$pids" ]]; then | |
| echo "Nothing listening on port $port" | |
| exit 0 | |
| fi | |
| for pid in $pids; do | |
| cmd="$(ps -p "$pid" -o comm= 2>/dev/null || echo '?')" | |
| echo "Killing $pid ($cmd) on port $port with SIG$signal" | |
| kill -"$signal" "$pid" 2>/dev/null || true | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment