Find and kill a process using a particular port
What/Why
Sometimes when I'm running services locally, I run into conflicts where "something is already using port XXXX". For this reason, I wrote a bash function to find and kill whatever process(es) using that port.
Use this function wisely, as you shouldn't just kill processes willy-nilly
How
Here is the script:
kill() {
PID=$(lsof -i:$1 | grep 'username' | awk '{print $2}')
if [ $PID ]; then
kill $PID;
fi
}
I'm using lsof
to list processes by port number, grep
to isolate the lines of output that contain actual processes (not the header), and finally awk
to return the PID value.
This is then stored in a variable, and if it exists, then it will attempt to kill that process.
Remember to replace username with your username. You can also grep
on other values, depending on what program you know is using the port (e.g. 'ruby' or 'Chrome').
Written by Derryl Carter
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Shell
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#