Shell · Inline
Free Up Port
Stops the processes listening on a TCP port, such as a dev server left running on 3000. Asks before it runs.
- Language
- Shell
- Output
- Inline
- Keyword
killport- Arguments
- Port
- Confirmation
- Asks before running
- Licence
- MIT
- Author
- Docktopus
- File
- free-up-port.zsh (1.2 KB)
- Downloads
- 0
In Docktopus: Settings → Scripts → Browse Community Scripts. Read the source before you run any script.
Source
free-up-port.zsh · sha256 89aa8b9b8bf0…#!/bin/zsh
# @docktopus.schemaVersion 1
# @docktopus.title Free Up Port
# @docktopus.mode inline
# @docktopus.icon xmark.octagon
# @docktopus.keyword killport
# @docktopus.description Stops the processes listening on a TCP port, such as a dev server left running on 3000. Asks before it runs.
# @docktopus.argument1 {"type": "text", "placeholder": "Port"}
# @docktopus.needsConfirmation true
# @docktopus.author Docktopus
port="$1"
if [[ "$port" != <-> ]] || (( port < 1 || port > 65535 )); then
echo "“$port” is not a port number." >&2
exit 1
fi
pids=(${(f)"$(/usr/sbin/lsof -nP -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null)"})
if (( ${#pids} == 0 )); then
echo "Nothing is listening on port $port."
exit 0
fi
for pid in $pids; do
name=$(/bin/ps -p "$pid" -o comm= 2>/dev/null)
if kill "$pid" 2>/dev/null; then
echo "Stopped ${name:t} (PID $pid)."
else
echo "Could not stop ${name:t} (PID $pid). It may belong to another user." >&2
fi
done
# Give processes a moment to exit, then report anything still holding the port.
sleep 1
if /usr/sbin/lsof -nP -tiTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then
echo "Port $port is still in use. Run again to retry."
else
echo "Port $port is free."
fi