Skip to content

Instantly share code, notes, and snippets.

@cdcabrera
Last active July 9, 2017 02:00
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 cdcabrera/16105c5fc2ce5c65f50fe64dff69e013 to your computer and use it in GitHub Desktop.
Save cdcabrera/16105c5fc2ce5c65f50fe64dff69e013 to your computer and use it in GitHub Desktop.
LSOF kill processes associated with a port

Process Kill

Basic kill for those times you just can't seem to stop a process. Originally written to help stop Node processes.

Basic Use

The script has a couple of options. Use a "port"

$ [PROCESSKILL] -p 9000

or kill a process "starting with" a string, like a node process...

$ [PROCESSKILL] -c node

The option argument for port, -p, is given preference over the string, -c option.

#!/usr/bin/env bash
#
# chmod it by:
# $ chmod +x [YOURFILE]
#
# main()
#
{
while getopts p:c: option;
do
case $option in
p)
PORT=$OPTARG
;;
c)
STARTSWITH=${OPTARG// }
;;
\?)
exit 1;
;;
esac
done
if [ "$PORT" -eq "$PORT" ] 2>/dev/null; then
lsof -i:$PORT
echo Killing \":$PORT\"
kill $(sudo lsof -t -i:$PORT) || sudo kill $(sudo lsof -t -i:$PORT) || echo Process not found for \":$PORT\"
elif [ -n "$PORT" ]; then
echo Option should be an int, not \"$PORT\"
fi
if [ -z "$PORT" ] && [ -n "$STARTSWITH" ]; then
lsof -c $STARTSWITH
echo Killing process\(es\) starting with \"$STARTSWITH\"
kill $(sudo lsof -t -c $STARTSWITH) || sudo kill $(sudo lsof -t -c $STARTSWITH) || echo Process not found for \"$STARTSWITH\"
elif [ -z "$PORT" ]; then
echo Option should NOT be an \"empty\" string
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment