How to write a shscript to kill -9 a pid which is found via lsof -i
There is a -t
(terse) option in lsof
, which seems to do exactly what you are looking for i.e.
$ sudo lsof -ti tcp:80
1387
4538
4539
See man lsof
-t specifies that lsof should produce terse output with process
identifiers only and no header - e.g., so that the output may
be piped to kill(1). -t selects the -w option.
Assuming you have the necessary permissions, you can pass the result to kill
as a list of PIDs with command substitution:
kill -9 $(lsof -ti tcp:80)
Do not forget the --no-run-if-empty
option of kill :)
lsof -ti :8080 | xargs --no-run-if-empty kill -9
That way kill will only be run there is a process listening, not need to do the check yourself.
lsof -i tcp:8080
produces the output, then | egrep -v "COMMAND PID USER"
drops the header line, then | awk '{print $2}'
prints the 2nd field, | sort -n
prepares the numbers for | uniq
, which only outputs each unique PID once. Putting it all together gives:
lsof -i tcp:8080 | egrep -v "COMMAND PID USER" | awk '{print $2}' | sort -n | uniq
But, pkill -KILL tomcat
or killall -KILL tomcat
is easier.