Skip to content

Instantly share code, notes, and snippets.

@gemfarmer
Last active March 23, 2017 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gemfarmer/3ed4c09689e71e0aed7e2c071352b60a to your computer and use it in GitHub Desktop.
Save gemfarmer/3ed4c09689e71e0aed7e2c071352b60a to your computer and use it in GitHub Desktop.
Bash script that kills a process

Usage

This script will kill the pid process that is responsible for keeping a port open. Use as follows to kill the process that corresponds to a given port:

./killport [PORT]

If the command killport is not recognized, make it executable:

chmod +x ./killport
#!/usr/bin/env bash
#################################################
# Lists the process running on the passed port #
# and then confirms whether you want to kill it #
#################################################
#Get the port that the user passed in
port=$1
if [[ ${#port} == 0 ]]; then
echo "Kills a service running on the specified port."
echo "usage: killport PORT"
exit;
fi
# Get everything running on this port
lsofcmd="lsof -i :$port"
# echo the command, and then iterate through each line of the output
counter=0
$(echo $lsofcmd) | while read -r line; do
echo $line
counter=$((counter+1)) # We want to skip the first line, as the first line is the column headers, from lsof
if [[ $counter > 1 ]]; then
procname=$(echo $line | awk '{print $1}')
pid=$(echo $line | awk '{print $2}')
echo "Killing $procname process with PID: $pid"
kill -9 $pid;
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment