I'm very very new to the terminal script world. Here's what I want to do:
1) Find out the process that's using a given port (8000 in this case)
2) Kill that process
Pretty simple. I can do it manually using:
lsof -i tcp:8000 -- get the PID of what's using the port
kill -9 $PID -- terminate the app using the port
For reference, here's exactly what gets returned when using lsof -i tcp:8000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
php 94735 MyUser 5u IPv6 0x9fbd127eb623aacf 0t0 TCP localhost:irdmi (LISTEN)
Here's my problem: how do I capture the PID value from lsof -i tcp:8000
so that I can use that variable for the next command? I know how to create variable that I assign... just not ones that are dynamically made.
The thing you’re looking for is called command substitution. It lets you treat the output of a command as input to the shell.
For example:
$ mydate="$(date)"
$ echo "${mydate}"
Mon 24 Feb 2014 22:45:24 MST
It’s also possible to use `backticks`
instead of the dollar sign and parentheses, but most shell style guides recommend avoiding that.
In your case, you probably want to do something like this:
$ PID="$(lsof -i tcp:8000 | grep TCP | awk '{print $2}')"
$ kill $PID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With