Skip to content

Instantly share code, notes, and snippets.

@ubermajestix
Created September 10, 2015 16:19
Show Gist options
  • Save ubermajestix/15911791002c2ecc4264 to your computer and use it in GitHub Desktop.
Save ubermajestix/15911791002c2ecc4264 to your computer and use it in GitHub Desktop.
Finds and kills a process on a port using lsof (only tested on OSX)
#!/usr/bin/env bash
# Kills a process running on a given port
#
# Examples:
# A process is running on port 3000, but we're not sure we want to kill it yet:
#
# $ killport 3000
# > Found pid 27448 running on 3000
# > tyler.montgomery 27851 0.0 0.0 2441988 684 s014 S+ 3:54PM 0:00.00 grep 27448 tyler.montgomery 27448 0.0 1.4 2727220 227784 s009 S+ 3:53PM 0:08.22 puma [app] init ...
# > Pass -f to kill process
#
# Now to kill the process, pass -f
#
# $ killport 3000 -f
# > Found pid 27448 running on 3000
# > tyler.montgomery 27851 0.0 0.0 2441988 684 s014 S+ 3:54PM 0:00.00 grep 27448 tyler.montgomery 27448 0.0 1.4 2727220 227784 s009 S+ 3:53PM 0:08.22 puma [app] init ...
# > Process killed
#
# Nothing is running on target port
# $ killport 3000 -f
# > Nothing running on 3000
port=$1
killit=$2
pid=`lsof -t -i:$1`
if [ -n "$pid" ]
then
echo "Found pid $pid running on $port"
process=`ps aux | grep $pid`
echo $process
if [ "$killit" = "-f" ]
then
kill -9 $pid
echo "Process killed"
else
echo "Pass -f to kill process"
fi
else
echo "Nothing running on $port"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment