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?
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?
I usually just use pgrep and pkill
You could kill processes by name using
pkill
orkillall
, check their man pages.A bit of a different approach would be something like this:
This will avoid the
1
Error-Code returned from thekillall
command, if the process did not exist. Theecho
part will only come into action, ifkillall
returns1
, while itself will return0
(success).Check if the process exist with
pidof
. If it does, kill it:Exit code is always 0 after executing the above command.
Small Script I have created with R&D. I hope you will like it
save it with some name like
script.sh
thenThen give your process name.
Note: I have tried many times with this and its fine.
Use
pkill
with option-f
Option
-f
is the pattern that is normally matched against the process name.or
try using:
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.
I would use:
The
xargs -r
tells to run kill only if there is input. Theps --no-header -eo pid,cmd
gets the output into a better format for parsing.