Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 2 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 '14 at 13:11
$() and `` are equivalent. – fedorqui Jul 29 '14 at 13:13
That worked... thank you :) – user3887720 Jul 29 '14 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


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.