Shell script gives error [: !-z: unary operator expected while execute

bashscriptterminal

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:

  • The first line should be #!/bin/bash (which together with chmod pkill.sh will allow you to run ./pkill.sh mongod directly)
  • Whitespace is important in 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 call kill if the string is non-empty?

PS: Also, using pgrep or even pkill instead of the pipes will make things a lot easier here.