Skip to content

Instantly share code, notes, and snippets.

@thmsmlr
Created February 1, 2022 19:01
Show Gist options
  • Save thmsmlr/1ef550e4c84e0cf507f1e6dc945f1efa to your computer and use it in GitHub Desktop.
Save thmsmlr/1ef550e4c84e0cf507f1e6dc945f1efa to your computer and use it in GitHub Desktop.
killport
#!/bin/sh
usage() {
cat >&2 << EOF
killport: kill -9 any process that is bound to a local port
Usage:
killport <port>
EOF
}
case "$1" in
"-h") usage && exit 0 ;;
"--help") usage && exit 0 ;;
esac
PORT=$1
[ -z "$PORT" ] && echo "killport: Please provide a <port>!" && usage && exit 1 >&2
[ "$PORT" -lt 1 ] && echo "killport: port must be a postive integer!" && usage && exit 1 >&2
PID=$(lsof -i tcp:$PORT | tail -n1 | awk '{print $2}')
NAME=$(lsof -i tcp:$PORT | tail -n1 | awk '{print $1}')
[ -z "$PID" ] && echo "No process bound to $PORT, doing nothing" && exit 0 >&2
echo "Killing process $NAME (PID: $PID) that is bound to local port $PORT"
kill -9 $PID
@thmsmlr
Copy link
Author

thmsmlr commented Feb 1, 2022

Something i keep around in my ~/bin that helps me when i'm developing. Sometimes you accidentally orphan a server that holds on to a port. This helps you quickly find it and kill it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment