oblivion
oblivion

Reputation: 6548

How to kill processes running on a port only if the port is open?

Currently, I am able to kill a process running on a port with:

//other scripts that should be executed
...........................
sudo kill $( sudo lsof -i:9005 -t )
...........................
//other scripts that should be executed

Now, I want to first test if the port 9005 is actually open and then only try to kill it.If the port is not open, I don't want to execute the kill script. I want to ensure that subsequent scripts are executed irrespective of whether the port is open or close. So, I am looking for something like:

//other scripts that should be executed
.............
<test-if-port-9005-is-open>  && sudo kill $( sudo lsof -i:9005 -t )
.............
// other scripts that should be executed

How can I achieve this ?

Upvotes: 0

Views: 6033

Answers (2)

tripleee
tripleee

Reputation: 189407

If I understand your question correctly, the output of lsof -i:9005 -t will by definition be empty when the port is not open. xargs on Linux has an option for handling this:

sudo lsof -i:9005 -t | xargs -r sudo kill

or you can simply check the exit code of lsof; it will be non-zero to signal an error if it didn't find anything to report:

if pids=$(sudo lsof -i:9005 -t); then
    sudo kill $pids
fi

Upvotes: 5

fr3dch3n
fr3dch3n

Reputation: 429

You could do something like this:

nc -zv 127.0.0.1 9005 && sudo kill $( sudo lsof -i:9005 -t )

It kills the process if a tcp-connection was successful on the provided port. Then it moves on. As tested on macOS High Sierra.

Upvotes: 5

Related Questions