1

Sometimes I need to kill a specific process which is listening on a known port in order to free that port up.

When I execute sudo lsof -n -i :1084, in order to get the PID of the process listening on port 1084, I get the following result

COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1603   pi   11u  IPv4  26101      0t0  TCP *:1084 (LISTEN)
sshd    1603   pi   12u  IPv6  26102      0t0  TCP *:1084 (LISTEN)

With grep -P 'IPv4.+LISTEN' I can obtain the line where a process is listening on that port, using IPv4

Executing

sudo lsof -n -i :1084 | grep -P 'IPv4.+LISTEN'

returns

sshd    1603   pi   11u  IPv4  26101      0t0  TCP *:1084 (LISTEN)

How can I now get 1603 so I can pass that one to kill?

I tried with grep, sed (sudo lsof -n -i :1084 | grep -P 'IPv4.+LISTEN' | sed -E 's/sshd\ +(\d+)\ /\1/g') but I just don't know how.

There must be a command like sudo lsof -n -i :1084 | grep -P 'IPv4.+LISTEN' | xargs --no-run-if-empty kill {$second_argument}' which would allow me to archive that goal, any ideas?

Also, if it's not a solution with sed, what would a solution using sed look like (I could use that in other cases)?

1

How can I now get 1603 so I can pass that one to kill?

That is a job for awk:

sudo lsof -n -i :1084 | grep -P 'IPv4.+LISTEN' | awk '{print $2}'

Further Reading

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.