I've created a bash script to kill the active process searching by name
pkill.sh
#~/bin/bash
pro=`ps aux | grep $1 | grep -v sh | grep -v grep | awk '{print $2}'`
if [ !-z "$pro" ]
then
echo $1 process is not running
else
kill -9 $pro
echo $1 process killed forecfully, process id was $pro.
fi
and execute this shell script in terminal ( v 2.8) as following
sh pkill.sh mongod
the job is done, but it gives the error too
pkill.sh: line 3: [: !-z: unary operator expected kill: usage: kill
[-s sigspec | -n signum | -sigspec] pid | jobspec … or kill -l
[sigspec] mongod process killed forecfully, process id was .
why this script gives an error?
I tried with
if[[ !z "$pro ]]
but no help.
Please tell me how to write exactly valid bash script
Best Answer
There are three issues I can see:
#!/bin/bash
(which together withchmod pkill.sh
will allow you to run./pkill.sh mongod
directly)bash
, try[ ! -z "$pro" ]
:-)-z
tests for an empty string, so! -z
tests for a non-empty one. Ignoring for a moment that-n
does the same thing: shouldn't you callkill
if the string is non-empty?PS: Also, using
pgrep
or evenpkill
instead of the pipes will make things a lot easier here.