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.

Tags:

Bash

Scripts