A command can be formulated like this:
netstat -lpn | grep ":1234\b" | awk '{sub(/\/.*/, "", $NF); print $NF}' | xargs -i kill -kill {}
Explanation:
netstat -ltpn
- This lists the listening ports (
l
) on TCP (t
) and their programs (p
) without resolving port numbers to names (n
).
grep ":1234\b"
- This searches for
:1234
followed by a boundary (\b
), indicating the end of the word (or number, in our case). This makes sure that we don't catch :12345
for example.
awk '{sub(/\/.*/, "", $NF); print $NF}'
This
- substitutes
sub(/regex/,"replacewith", #fieldnumber)
- this regex
\/.*
- with nothing
""
- in the field
$NF
, which means the last field (i.e. the field that contains PID/program
)
- then prints it
print $NF
.
The regex \/.*
matches a literal /
and everything after it, and then we're replacing it with nothing, essentially deleting it, so we're left with only the PID number in that field.
xargs -i kill -kill {}
xargs -i
is a program that allows you to make the output of the previous command act as the input to another command. Our command is kill -kill {}
where {}
indicates "the output from the previous command in the pipeline", which is our PID number.
Note: this whole command might be a little bit dangerous because you might accidentally kill something you didn't want to. It could use with a little bit more sanitization. Just make sure you get the correct port number when using it.
If you want to make this into a function, you can add the following to your ~/.bashrc
:
killatport(){
netstat -lpn | grep ":$1\b" | awk '{sub(/\/.*/, "", $NF); print $NF}' | xargs -i kill -kill {}
}
Save and apply the changes using source ~/.bashrc
. Now, you can use the function like this:
killatport 8088
mvn jetty:stop
could fail if the instance hasOutOfMemoryError
. When I restart java servlets it happens that the port is not available even at a regular stop such asmvn jetty:stop
. Sometimes the process can getOutOfMemoryError
and won't free the TCP port at a regular shutdown such asmvn jetty:stop
.mvn jetty:stop
is not the same as sending SIGTERM, and the jvm should still be able to process SIGTERM even though its application(s) is out of mem.