Skip to content

Instantly share code, notes, and snippets.

@zdk
Last active November 20, 2023 02:11
Show Gist options
  • Save zdk/eb576c5af67fa3974d41489ad9efedc3 to your computer and use it in GitHub Desktop.
Save zdk/eb576c5af67fa3974d41489ad9efedc3 to your computer and use it in GitHub Desktop.
Kill multi ports
killport() {
while test $# -gt 0
do
port_number=$1
pid=$(lsof -P | grep ':'$port_number'[[:space:]](LISTEN)' | awk '{print $2}')
if ! kill -QUIT $pid > /dev/null 2>&1; then
echo -e "\e[0;31mNo process running on \e[0m $port_number port" >&2
else
echo -e "Kill $port_number \e[0;32msuccessfully\e[0m"
fi
shift
done
}
lsport() {
lsof -Pn -i4 | grep '(LISTEN)' | awk 'BEGIN{print "Name PID Host:Port"};{print $1 " " $2 " " $9}'
}
# Usage:
# Open terminal
# Add above functions to your ~/.zshrc or ~/.bashrc or ~/.profile
#
# ❯ killport 3000 5173
# Kill 3000 successfully
# Kill 5173 successfully
# ❯ killport 5174
# No process running on 5174 port
# ❯ lsport
# Name PID Host:Port
# postgres 546 127.0.0.1:5432
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment