Reputation: 161
I am trying to automate one of the jobs I am facing again and again. There are some ports which are sometimes not closed correctly by some previous jobs..
Lets say port 5000,5001
WHat I want to do is see if these ports are open
and kill these ports if they are open
So right now, I am doing
lsof -i :5000
and
kill -9 pid1
kill -9 pid2
and so on..
Is there a way to pass 5000 and 5001 as arguments and automate this process
Upvotes: 1
Views: 535
Reputation: 4739
If you want to automate it as you use it do something like this.
Create a bash script, for example call it 'killMyPorts' and add the following content:
#!/bin/bash
kill -9 `lsof -i :"${1}" | awk '{if (NR!=1) {print $2}}'`
Once you made the script executable (chmod u+x), you can execute it as follows:
./killMyPorts 5000
Upvotes: 2
Reputation: 295736
fuser
can do this job for you.
kill_port_users() {
for port; do
fuser -n tcp -k "$port"
done
}
kill_port_users 5000 5001
Upvotes: 1