5

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 }'

4

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 }')
  • kill -9 ps | grep "server1" | grep -v grep | awk '{ print $1 }'... Using back tics instead of braces – user3887720 Jul 29 '14 at 13:11
  • $() and `` are equivalent. – fedorqui Jul 29 '14 at 13:13
4

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.

0

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}'

Script:

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

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

  • You might describe the link contents here. – Tomasz Sep 27 '16 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.