How to kill a process in shell script which is running through cron?

I have a shell script which runs in cronjob. This shell script has to kill a process which is running and start the new process again.

When I run the script manually it works perfectly fine, but when it runs through cron it does not kill the old process but starts a new process along with the old one.

I am using the below line of code to kill the process:

kill -9 ps | grep “server1” | grep -v grep | awk ‘{ print $1 }’

Asked By: user3887720


You have to indicate what to kill:

kill -9 $(ps | grep "server1" | grep -v grep | awk '{ print $1 }')

You can also use the trick:

kill -9 $(ps | grep "server[1]" | awk '{ print $1 }')
Answered By: fedorqui

In the purest form, you can use

pkill server1

That assumes server1 is actually the process name, not just somewhere in the command line – otherwise add an -f.

pkill -f server1CommandArgument

But wait!

You can test what pkill will match and kill with the command pgrep – which is technically almost the same. The difference it: instead of killing, it prints the PID.

Try these – list the matching PIDs:

pgrep server1

-l lists the process name too, not only the PID:

pgrep -l server1

-f matches the command line, not only the name:

pgrep -fl server1

When you want to kill the processes that are matched by pgrep,
leave out the -l, and add a signal, if you want something else than the default SIGTERM, -15:

pkill -9 server1

As your example uses a plain ps command, which matches only processes on the current terminal by default, take care what is matched by your command, as pgrep and pkill are not matching only processes on the current terminal.

A side note on using kill -9 – it is the most violent way to kill;
are you sure that’s actually needed?

That may not matter, depending on what kind of program killed. But you should not do it without a good reason to a program/server that may save any data do files, writes lock files, etc. As long as a programm does not badly hang, a kill using the default signal -15 would do.

Answered By: Volker Siegel

Inside shell script you have to skip sh also. Below command worked for me.

ps -aef | grep $1 | grep -v sh| grep -v grep| awk '{print $2}'


var=`ps -aef | grep $1 | grep -v sh| grep -v grep| awk '{print $2}'`
if [ !-z "$var"]
  echo $1 process is not running 
  kill -9 $var
  echo $1 process killed forcefully, process id $var.

Reference: Force Kill linux process in shell script can go through the article for full explanation.

Answered By: Siva Kumar Reddy G
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.