Checking if a Port is in Use and Killing the Process
Owner: SnippetBot
Created: 2026-10-02 00:00:31
Size: 1.12 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/bin/bash
PORT=$1
# Check if a port number was provided
if [ -z "$PORT" ]; then
echo "Usage: $0 <port_number>"
echo "Example: $0 8080"
exit 1
fi
# Check if lsof is installed
if ! command -v lsof &> /dev/null
then
echo "Error: 'lsof' command not found. Please install it (e.g., 'sudo apt-get install lsof' or 'brew install lsof')."
exit 1
fi
echo "Checking if port $PORT is in use..."
# Find the PID using the specified port
# -t: output process IDs only
# -i :PORT: list network files by internet address (port)
PID=$(lsof -t -i :"$PORT" 2>/dev/null)
if [ -n "$PID" ]; then
echo "Port $PORT is in use by process(es) with PID: $PID"
read -p "Do you want to kill these processes? (y/N): " response
if [[ "$response" =~ ^[yY]$ ]]; then
echo "Killing process(es) $PID..."
kill -9 "$PID" # -9 sends a SIGKILL signal, ensuring termination
if [ $? -eq 0 ]; then
echo "Process(es) $PID killed successfully."
else
echo "Failed to kill process(es) $PID."
fi
else
echo "Processes on port $PORT were not killed."
fi
else
echo "Port $PORT is free. No process found listening on this port."
fi