BASH
Find and Kill a Specific Process by Name or Port
A useful bash script to locate a running process by its name (full command) or a specific port it's listening on, and then safely terminate it.
#!/bin/bash
# Find and kill a process by name or port
SEARCH_TERM="$1"
KILL_SIGNAL="-TERM" # Or -KILL, -INT for stronger termination
if [ -z "$SEARCH_TERM" ]; then
echo "Usage: $0 <process_name_or_port>"
echo "Example: $0 'node server.js'"
echo "Example: $0 3000"
exit 1
fi
echo "Searching for processes matching '$SEARCH_TERM'..."
PIDS=()
if [[ "$SEARCH_TERM" =~ ^[0-9]+$ ]]; then
# Search by port
echo "Searching by port $SEARCH_TERM..."
# lsof -t -i :PORT gets PIDs listening on that port
PIDS=$(lsof -t -i :"$SEARCH_TERM" 2>/dev/null)
else
# Search by process name/command
echo "Searching by process name '$SEARCH_TERM' ..."
# pgrep -f searches the full command line
PIDS=$(pgrep -f "$SEARCH_TERM" 2>/dev/null)
fi
if [ -z "$PIDS" ]; then
echo "No processes found matching '$SEARCH_TERM'."
exit 0
fi
echo "Found process(es) with PIDs: $PIDS"
for PID in $PIDS; do
if [ "$PID" == "$$" ]; then # Don't kill self
echo "Skipping self PID: $PID"
continue
fi
echo "Attempting to send $KILL_SIGNAL to PID $PID..."
kill "$KILL_SIGNAL" "$PID"
if [ $? -eq 0 ]; then
echo "Successfully sent $KILL_SIGNAL to PID $PID."
else
echo "Error sending $KILL_SIGNAL to PID $PID."
fi
done
echo "Process termination attempt completed."
exit 0
How it works: This script accepts a process name or a port number as an argument. It uses `pgrep -f` to find process IDs by command line or `lsof -t -i :<port>` to find PIDs listening on a specific port. Once PIDs are identified, it iterates through them, sending a specified kill signal (defaulting to `-TERM` for graceful termination) to each process, ensuring the script does not terminate itself. This is highly useful for managing development servers or stuck processes.