Write and use a simple bash script to kill a process to free up a port.
This article was first published on my dev.to page, check it here - https://dev.to/guha/kill-that-pesky-process-the-really-lazy-way-5eg.
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.