Ludisposed Ludisposed -4 years ago 72
Bash Question

Bash script to kill Port

At the moment I am learning SSH creating and listening of servers.
But I still tend to do it wrong a lot and afterwards my Ports are still open. So I am writing a bash script to kill it, but I had a bug I was unable to solve... So any help is welcome.

The Script:

#!/bin/bash
pid=$(lsof -i:22 -t);set -f;a=(${pid})
for e in ${a[@]}
do
echo $e
kill $e || kill -9 $e
done


Behaviour

@
echo $e
the shell gives the correct PID

but when I do a
lsoif -i:22 -t
when the script is run the PID is still open.

What am I missing?

Answer Source

Since you are willing to kill with the -9 flag please replace the:

kill $e || kill -9 $e

with

kill -9 $e

As mentioned in nixCraft Logical OR

command1 || command2

command2 is executed if, and only if, command1 returns a non-zero exit status. In other words, run command1 successfully or run command2.

In the case of

kill $e || kill -9 $e

The first command (kill $e) didn't fail (as the pid was valid), hence the second command wasn't executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download