Home:ALL Converter>How can you use the unix kill command silently in a bash script?

How can you use the unix kill command silently in a bash script?

Ask Time:2012-02-23T04:23:10         Author:Jimmy

Json Formatter

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?

Author:Jimmy,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/9402361/how-can-you-use-the-unix-kill-command-silently-in-a-bash-script
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
yy