i have this in my .zshrc which provides same functionality:
lk() {
if [ $# -eq 0 ]; then
local output=$(sudo lsof -iTCP -sTCP:LISTEN -n -P)
elif [ $# -eq 1 ]; then
local output=$(sudo lsof -iTCP -sTCP:LISTEN -n -P | grep -i --color=always $1)
else
echo "find and kill processes listening on ports. Usage: lk [pattern]"
return 1
fi
if [ -z "$output" ]; then
echo "No listening processes found."
return 0
fi
# Show header + results
echo "$(sudo lsof -iTCP -sTCP:LISTEN -n -P | head -1)"
echo "$output"
echo ""
# Extract unique PIDs (skip the header row if no grep was applied)
local pids=($(echo "$output" | awk '{print $2}' | grep -E '^[0-9]+$' | sort -u))
if [ ${#pids[@]} -eq 0 ]; then
echo "No PIDs found."
return 0
fi
echo "PIDs to kill: ${pids[*]}"
echo -n "Kill these ${#pids[@]} process(es)? [y/N] "
read -r confirm
if [[ "$confirm" =~ ^[Yy]$ ]]; then
for pid in "${pids[@]}"; do
echo "Killing PID $pid..."
sudo kill -9 $pid
done
echo "Done."
else
echo "Aborted."
fi
}I have added quite a lot of functionality beyond listing and killing ports. Please check out the readme, it may convince you to try it out.