Skip to content

Instantly share code, notes, and snippets.

@codepunkt
Last active June 7, 2016 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codepunkt/8c851fb334e3bc0ee221d9534a48a433 to your computer and use it in GitHub Desktop.
Save codepunkt/8c851fb334e3bc0ee221d9534a48a433 to your computer and use it in GitHub Desktop.
Kill process running on a port
#!/bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'
if [ $# -eq 0 ] ; then
echo -e "${RED}Error: No port given${NC}"
exit 1
fi
if ! [[ $1 =~ ^[0-9]+$ ]] ; then
echo -e "${RED}Error: Port is not a number${NC}"
exit 1
fi
PID="$(lsof -i :$1 -t)"
if [[ -z "${PID// }" ]] ; then
echo -e "No process running on port ${YELLOW}${1}${NC}"
else
echo -e "Process with pid ${GREEN}${PID}${NC} running on port ${YELLOW}${1}${NC}"
echo -e "Killing process…"
kill -- -$(ps -o pgid= $PID | grep -o [0-9]*)
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment