I have a shell script to check port status. After checking the port if it is busy then will kill it.
#check port and kill
checkPort(){
check=$(sudo netstat -nlpt | grep 2020 | awk '{print $6}')
word="LISTEN"
killProcess=$(sudo netstat -nlpt | grep 2020 | awk '{print $7}' |
sed 's/.\{5\}$//' | sort -u | xargs -t kill -9)
if [[ "$check" == "$word" ]];
then
echo "killing the port 2020"
$killProcess
else
echo "Not Listen"
fi
}
When I run the $killProcess
variable I am getting errors. But if I put the full command as sudo netstat -nlpt | grep 2020 | awk '{print $7}' | sed 's/.\{5\}$//' | sort -u | xargs -t kill -9
inside the if
condition, it is working fine. What would be the mistake here?
The errors I get:
kill -9
Usage:
kill [options] <pid|name> [...]
Options:
-a, --all do not restrict the name-to-pid conversion to processes
with the same uid as the present process
-s, --signal <sig> send specified signal
-q, --queue <sig> use sigqueue(2) rather than kill(2)
-p, --pid print pids without signaling them
-l, --list [=<signal>] list signal names, or convert one to a name
-L, --table list signal names and numbers
-h, --help display this help and exit
-V, --version output version information and exit
I put xargs -i kill -kill {}
instead of xargs kill -9
. Works fine. Is it a good practice?
The syntax
var=$(command)
will runcommand
and assign its output to the variable$var
. This means that this line in your script:will always run this pipeline which ends with the
kill
command, and assign its output to$killprocess
. Since thekill
command has no output, this line later will never do anything:What you want to do is
killProcess="sudo netstat ... | xargs -t kill -9
. But there are other issues with your command as well. First of all, it will match any lines containing 2020, but you only want cases where2020
is the port. What if it is the PID instead?Here is a working version of your function with a few changes:
This can now take a parameter, so run it as
checkport
to check port 2020, andcheckport 22
will check port 22. It also first tries to kill gracefully (ou should always avoidkill -9
unless absolutely necessary) and only useskill -9
if that fails.