Monday, May 16, 2016

Automatically kill the process running on port $PORT in shell

Write this in a file and save it as filename.sh
Now, you can kill whatever process is running on the port you enter.
Note: this only works on *nix systems (lsof doesn't work in girt bash either).

     # kill the process using the desired port
     if [ -z "$1" ]
     then
       printf "Please select a port number to kill by, ie 8263:"
       read PORT
     else
       PORT=$1
     fi
     
     printf "\nThings running on port:$PORT\n==========================\n"
     STR=$(lsof -i:$PORT)
     if [ -z "$STR" ]
     then
       printf "Nothing was running\n"
     else
       printf "Killing process on port: $PORT\n==========================\n"
       kill -9 $(lsof -t -i:$PORT)
       lsof -i:$PORT
     fi
     
     read -p "Done. Press enter to continue..."