Skip to content

Instantly share code, notes, and snippets.

@floriankraemer
Created December 11, 2024 13:30
Show Gist options
  • Save floriankraemer/e6f8c75c76f5b03719d710915d1e637d to your computer and use it in GitHub Desktop.
Save floriankraemer/e6f8c75c76f5b03719d710915d1e637d to your computer and use it in GitHub Desktop.
Kills a process running on a given port
#!/bin/bash
# Check if a port number is passed as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <port_number>"
exit 1
fi
PORT=$1
# Find the process ID (PID) occupying the given port
PID=$(sudo lsof -t -i:$PORT)
# Check if a process is found
if [ -z "$PID" ]; then
echo "No process is occupying port $PORT."
exit 0
fi
echo "Process ID $PID is occupying port $PORT."
# Kill the process
kill -9 $PID
if [ $? -eq 0 ]; then
echo "Successfully killed process $PID."
else
echo "Failed to kill process $PID."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment