I'm trying to check if a particular process is running, and if it is, try and kill it.
I've come up with the following so far:
PID=$(ps aux | grep myprocessname | grep -v grep | awk '{print $2}')
if [ -z $PID];
then
echo Still running on PID $PID, attempting to kill..
kill -9 $PID > /dev/null
fi
However when I run this, I get the following output:
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
What is the best way to kill a running process on unix silently?
John :
The answer is easier\nThe program \"killall\" is part of almost any distribution. \n\nExamples:\n\nkillall name_of_process &> /dev/null\nkillall -9 name_of_process &> /dev/null\n(( $? == 0)) && echo \"kill successful\";\n\n\nNow there also is \"pkill\" and \"pgrep\"\nExample:\n\npkill -9 bash &> /dev/null\n(( $? == 0)) && echo \"kill successful\";\n\n\nExample:\n\nfor pid in $(pgrep bash); do\n kill -9 $pid &> /dev/null\n (( $? == 0)) && echo \"kill of $pid successful\" || echo \"kill of $pid failed\";\ndone\n\n\nAnd last as you used \"ps\" in your example, here a better way to use it without the requirement of \"grep\" \"grep -v\" and \"awk\":\n\nPIDS=\"$(ps -a -C myprocessname -o pid= )\"\nwhile read pid; do \n kill -9 $pid &> /dev/null\n ((!$?)) && echo -n \"killed $pid,\"; \ndone <<< \"$p\"\n\n\nAll those listed methods are better than the long pipe-pipe-pipe imho",
2012-02-22T20:30:33
Mat :
[ -z $PID]\n\n\nis true if $PID is empty, not the other way around, so your test is inverted.\n\nYou should be using pgrep if you have that on your system too. (Or even better: pkill and stop worrying about all that shell logic.)",
2012-02-22T20:26:25