I often do e.g.
sudo netstat -lpn |grep :8088
view the output
tcp6 0 0 :::8088 :::* LISTEN 11189/java
and then
sudo kill -kill 11189
I'd like to have a more convenient command exactly like killatport 8088
that uses the tcp port number as a variable and that I can make as an alias to a pipeline that does what I want, but how do I get the PID from the output and pipe it to the kill command? I suppose I might be able to use awk to get the PID from the output from netstat, but how do I safeguard and make an exact port match so that the input 80 won't match 8080 and likewise? Should I make it a C program instead? Or is there already a small utility like this?
fuser can do that:
A command can be formulated like this:
Explanation:
netstat -ltpn
l
) on TCP (t
) and their programs (p
) without resolving port numbers to names (n
).grep ":1234\b"
: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
sub(/regex/,"replacewith", #fieldnumber)
\/.*
""
$NF
, which means the last field (i.e. the field that containsPID/program
)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 iskill -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
:Save and apply the changes using
source ~/.bashrc
. Now, you can use the function like this: