25

Currently, I use a 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?

Pablo Bianchi
  • 17,371

9 Answers9

33

I usually just use pgrep and pkill

if pgrep myServer; then pkill myServer; fi
boutch55555
  • 1,226
10

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

enzotib
  • 96,093
9

A bit of a different approach would be something like this:

killall PROCESS || echo "Process was not running."

This will avoid the 1 Error-Code returned from the killall command, if the process did not exist. The echo part will only come into action, if killall returns 1, while itself will return 0 (success).

Anwar
  • 77,855
codepleb
  • 602
1

Use pkill with option -f

pkill -f myServer

Option -f is the pattern that is normally matched against the process name.

Chase T.
  • 141
  • 3
1

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

#!/bin/bash

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

save it with some name like script.sh then

chmod +x script.sh
./script.sh

Then give your process name.

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

Pablo Bianchi
  • 17,371
Raja G
  • 105,327
  • 107
  • 262
  • 331
1

Check if the process exist with pidof. If it does, kill it:

(! pidof process_name) || sudo kill -9 $(pidof process_name)

Exit code is always 0 after executing the above command.

Juuso Ohtonen
  • 151
  • 1
  • 4
0
pkill -9 -f jboss || true

or

pkill -9 -f tomcat || true 
Pablo Bianchi
  • 17,371
-1

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.

-1

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.

Arcege
  • 5,618