Created
July 28, 2025 20:23
-
-
Save metaphore/4cdd69bacaadf5648958e002af99c226 to your computer and use it in GitHub Desktop.
Free network socket with the specified port by killing the occupied process(es).
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
| #!/bin/bash | |
| # Usage: free_port.sh <PORT> [PROTOCOL] | |
| # PROTOCOL: tcp | udp | (anything lsof -i:PORT would accept, e.g. "rpc", "icmp", etc.) | |
| # If PROTOCOL is omitted, all protocols on that port will be targeted. | |
| if [ -z "$1" ]; then | |
| echo "Usage: $0 <PORT> [PROTOCOL]" | |
| exit 1 | |
| fi | |
| PORT=$1 | |
| PROTO=$2 | |
| # build the -i filter: either ":PORT" (all protocols) or "PROTO:PORT" | |
| if [ -n "$PROTO" ]; then | |
| FILTER="${PROTO}:${PORT}" | |
| else | |
| FILTER=":${PORT}" | |
| fi | |
| pids=$(lsof -i "$FILTER" -t) | |
| if [ -n "$pids" ]; then | |
| echo "Killing process(es) using port $PORT${PROTO:+/$PROTO}:" | |
| echo "$pids" | |
| echo "$pids" | xargs kill -9 | |
| else | |
| echo "No process is using port $PORT${PROTO:+/$PROTO}" | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment