2

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

  • 1
    Consider using shellcheck.net to assist finding issues with your shell script. – kojiro Dec 9 '17 at 1:20
3

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.

  • Thank you for quick help . Can you please provide syntax for pgrep and pkill are these inbuilt commad do the same thing? – pro.mean Dec 8 '17 at 20:04
  • @pro.mean, In Terminal i.e. man command, e.g., man pkill – user3439894 Dec 8 '17 at 20:06
  • @pro.mean Basically pkill -9 mongod :-) – nohillside Dec 8 '17 at 20:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .