killport.sh 667 Bytes
#!/bin/bash

# Kill processes listening on given ports

PORTS=$@
PIDS=""

function killDaemon {
	PORT=$1
	PID=`netstat -tlpn 2>/dev/null | egrep '^tcp' | awk -v PORT=$PORT  'match($4, ".*:"+PORT) { print $7 }' | awk -F '/' '{ print $1 }'`
	if [ "$PID" != "" ]
	then
		kill $PID
		PIDS="$PIDS $PID"
		echo "Killed daemon listening on port $PORT with pid $PID"
	else
		echo "No daemon listening at port $PORT"
	fi
}

function waitForDaemon {
	PID=$1
	while ps -p $PID > /dev/null
	do
		sleep 1
	done
	echo "Daemon with pid $PID stopped"
}

echo "===== Killing daemons ======"

for PORT in $PORTS
do
	killDaemon $PORT
done

for PID in $PIDS
do
	waitForDaemon $PID
done