Last active
May 16, 2023 12:07
-
-
Save syedmhashim/4870c5e557297de122b3ab3233c6d69f to your computer and use it in GitHub Desktop.
Kill a process which has a specific pid or is running on a specific port
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
print_usage() { | |
echo " | |
//////////////////////////////////////////////////////////////////////////////////// | |
* Kill a process which has a specific pid or is running on a specific port * | |
/////////////////////////////////////////////////////////////////////////////////// | |
Usage: | |
kill_process [OPTIONS] | |
Example | |
kill_process --port=8080 # Kill the process running on port 8080. | |
kill_process --pid=1111 # Kill the process with the pid 1111. | |
OPTIONS: | |
--port: The port on which the process is running. | |
--pid: The pid of the process to kill. | |
Note: Atleast one of the option, --pid, --port, is expected. If both are provided, --port will take precedence. | |
" | |
} | |
while [ $# -gt 0 ]; do | |
case "$1" in | |
-h|--help*) | |
print_usage | |
exit 0 | |
;; | |
--port=*) | |
port="${1#*=}" | |
;; | |
--pid=*) | |
pid="${1#*=}" | |
;; | |
*) | |
printf "\nError: Invalid argument: $1\n" | |
print_usage | |
exit 1 | |
esac | |
shift | |
done | |
if [[ ! -z $port ]]; then | |
pid="$(sudo lsof -Pi:$port -sTCP:LISTEN -t)" | |
if [ -z "$pid" ]; then | |
echo "kill_process: No process running on port, ($port)" | |
exit 1 | |
fi | |
fi | |
if [[ -z $pid ]]; then | |
echo "Atleast one of the option, --pid, --port, needs to be provided." | |
exit 1 | |
fi | |
sudo kill $pid -9 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment