Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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 }')
share|improve this answer
    
kill -9 ps | grep "server1" | grep -v grep | awk '{ print $1 }'... Using back tics instead of braces –  user3887720 Jul 29 at 13:11
    
$() and `` are equivalent. –  fedorqui Jul 29 at 13:13
1  
That worked... thank you :) –  user3887720 Jul 29 at 13:19

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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