A function to identify what process is using a specific port number
It finds the process name and its PID of the program using the port you specify.
just pass it the port number like so
check_port 443
check_port() {
local choice kill_choice pid name
if [ -z "$1" ]; then
read -p 'Enter the port number: ' choice
else
choice="$1"
fi
echo
# Getting the process information using lsof
while IFS= read -r line; do
if [[ "$line" == p* ]]; then
pid=${line#p}
elif [[ "$line" == c* ]]; then
name=${line#c}
fi
done < <(lsof -i :"$choice" -sTCP:LISTEN -Fpc)
if [ -n "$pid" ] && [ -n "$name" ]; then
echo "Process using port $choice: $name (PID: $pid)"
read -p "Do you want to kill the process? (yes/no): " kill_choice
shopt -s nocasematch
case "$kill_choice" in
yes|y) sudo kill -9 "$pid" ;;
no|n) return ;;
*) echo "Invalid option. Exiting." ;;
esac
shopt -u nocasematch
else
echo "No process is using port $choice."
fi
}
Posted Jan 18, 2024, 1:30 AM UTC
60