DEV Community

Cover image for Kill that pesky process, the really lazy way
Arghya Guha
Arghya Guha

Posted on

Kill that pesky process, the really lazy way

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

  1. cd to /usr/local/bin/.
  2. Create a new file and name it stop or anything else you want.
  3. 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.

  4. chmod +x stop to make the file executable. chmod 755 also works.

  5. Now you can use stop 9000 or any other port anytime on the terminal to stop whatever process is running on that port.

  6. 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)

Collapse
 
riscie profile image
riscie

Nice! ❀️
I've modified it a bit, so we don't need to write into a temp-file.

#!/bin/bash
pid=$(lsof -n -i :"$1" | tail -1 | awk '{print $2}')
if [[ -n $pid ]]
then
    kill -9 "$pid" && echo "Process which blocked port $1 was killed" || echo "Could not kill process blocking port $1..."
else
    echo "Seems like no process is blocking port $1"
fi

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!

Collapse
 
guha profile image
Arghya Guha

Great, that's even cleaner !