Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Currently I use line like this in my sh script file:

kill `ps aux | grep -F 'myServer' | grep -v -F 'grep' | awk '{ print $2 }'` 

But I wonder how to call it only if process (myServer here) is running?

share|improve this question

5 Answers 5

You could kill processes by name using pkill or killall, check their man pages.

share|improve this answer

try using:

sudo kill `pidof process_name`

where process_name is the name of the process you want to kill. What's great about this is that pidof will list the pid's of all processes matching the given name. Since kill accepts multiple pid's, it will kill of all of them in a single whim.

Let me know if this helps.

share|improve this answer
What if list is empty? (my main point was not to call kill at all if possible) –  myWallJSON Jan 31 '12 at 12:44
If the list is empty, kill will return an error code 1 and not kill anything. It would be the equivalent as trying to call kill with no arguments. You could add an if statement that first checks if pidof returns an empty list. If it does not return an empty list, call kill `pidof process_name. If it does return an empty list, skip the kill call. –  amandion Jan 31 '12 at 12:59

I usually just use pgrep and pkill

if pgrep myServer; then pkill myServer; fi
share|improve this answer
Why not pkill myServer or killall -q myServer? There's no downside to attempting to kill inexistent processes. –  David Foerster Oct 3 '14 at 15:57
It will not exit 0 if there is no process to kill, so it could break scripts. –  boutch55555 Oct 6 '14 at 15:00
Append || true then. –  David Foerster Oct 6 '14 at 15:01
True, but you won't have the flexibility to add a else to inform you the process was already dead. –  boutch55555 Oct 6 '14 at 16:57
What about if ! killall -q myServer; then echo ERROR; fi? –  David Foerster Oct 6 '14 at 17:07

I would use:

ps x --no-header -o pid,cmd | awk '!/awk/&&/myServer/{print $1}' | xargs -r kill

The xargs -r tells to run kill only if there is input. The ps --no-header -eo pid,cmd gets the output into a better format for parsing.

share|improve this answer

Small Script I have created with R&D. I hope you will like it


echo " Enter the process name:"
read $proc_name
if pgrep $proc_name
echo " $proc_name running "
pkill $proc_name
echo "$proc_name  got killed"
echo " $proc_name is not running/stopped "

save it with some name like script.sh then

chmod +x script.sh

Then give your process name.

Note: I have tried many times with this and its fine.

share|improve this answer
May I know whats wrong with this script and -ve vote needs an explanation please. –  Raja Oct 5 '14 at 5:33

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.