killport.sh
667 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/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