How to access the PID from an lsof.

Something like:

#!/bin/bash --

x=`lsof -Fp -i:1025`
kill -9 ${x##p}

Should do it. The 3rd line runs lsof using the -F option to get just the pid, with a leading p. The next line drops the leading p from the output of lsof and uses the result as the pid in a kill command.

Edit: At some point lsof was modified so the file descriptor preceded by an f is always output, whether you ask for it or not (which makes no sense to me, but what do I know). While you could put a | grep '^p' in the back quotes, an easier way is to use the -t option, as noted in fabianopinto's answer below.


And furthermore from @blm's and @Mosh Feu's answers:

lsof -i:1337 -Fp | head -n 1 | sed 's/^p//' | xargs kill

is what ended up doing the trick for me.

I recommend adding this as a bash function and aliasing it

alias kbp='killByPort'
killByPort() {
  lsof -i:$1 -Fp | head -n 1 | sed 's/^p//' | xargs kill
}

The lsof(8) man page says:

   -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.

You can use lsof -t -i:1025 | xargs kill -9.


man lsof says that you can use -F to specify fields to to be output for processing by other programs. So you can do something like

lsof -i:1025 -Fp | sed 's/^p//' | xargs kill -9

Tags:

Terminal

Bash