This is going to a be a quick one, today i'm going to share a small bash script that has saved me precious seconds or maybe even whole minutes over the years, every time i want to kill a process to free up a port.
Why
Something is already running at port 9000
I run into one of these every once in a while.
With me it often happens when i SUSPEND (CTRL+Z) my dev server instead of KILLING (CTRL+C) it.
The next steps would often involve hunting down the pid
of the process running on that port and killing it.
Easy enough, but here's something easier.
How
-
cd
to/usr/local/bin/
. - Create a new file and name it
stop
or anything else you want. -
Paste the following into it
#!/bin/bash touch temp.text lsof -n -i4TCP:$1 | awk '{print $2}' > temp.text pidToStop=`(sed '2q;d' temp.text)` > temp.text if [[ -n $pidToStop ]] then kill -9 $pidToStop echo "!! $1 is stopped !!" else echo "Sorry nothing running on above port" fi rm temp.text
*disclaimer: i didn't write the script, i merely adopted it. Credits below.
chmod +x stop
to make the file executable.chmod 755
also works.Now you can use
stop 9000
or any other port anytime on the terminal to stop whatever process is running on that port.Profit. Write once, use always.
Very briefly, what the script above does is find the pid
of the process running on the input port, copy it to a temp file and then read the temp file to find the pid
in it and kill it, finally deleting the temp file.
awk
for those curious is a programming language used for text processing.
Notes
- Here's my gist with the script above.
- Here's the stackoverflow answer i originally found this script at.
Title Image by Sammy-Williams over at Pixabay
Top comments (2)
Nice! ❤️
I've modified it a bit, so we don't need to write into a temp-file.
Also, we might need to use sudo for both lsof and kill if we do not own the process. But for the local dev environment it should be just fine like this.
Thanks again!
Great, that's even cleaner !