0

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Jimmy
  • 16,123
  • 39
  • 133
  • 213

3 Answers3

6
[ -z $PID]

is true if $PID is empty, not the other way around, so your test is inverted.

You should be using pgrep if you have that on your system too. (Or even better: pkill and stop worrying about all that shell logic.)

Hub 20xx
  • 401
  • 5
  • 14
Mat
  • 202,337
  • 40
  • 393
  • 406
5

The answer is easier
The program "killall" is part of almost any distribution.

Examples:

killall name_of_process &> /dev/null
killall -9 name_of_process &> /dev/null
(( $? == 0)) && echo "kill successful";

Now there also is "pkill" and "pgrep" Example:

pkill -9 bash &> /dev/null
(( $? == 0)) && echo "kill successful";

Example:

for pid in $(pgrep bash); do
 kill -9 $pid &> /dev/null
 (( $? == 0)) && echo "kill of $pid successful" || echo "kill of $pid failed";
done

And last as you used "ps" in your example, here a better way to use it without the requirement of "grep" "grep -v" and "awk":

PIDS="$(ps -a -C myprocessname -o pid= )"
while read pid; do 
  kill -9 $pid &> /dev/null
  ((!$?)) && echo -n "killed $pid,"; 
done <<< "$p"

All those listed methods are better than the long pipe-pipe-pipe imho

John
  • 7,507
  • 3
  • 52
  • 52
  • pkill is however not equal to killall; the former does a substring regex grep, which can be... potentially dangerous. – jørgensen Feb 23 '12 at 00:52
-1

Try if [ X$PID != X ] in your condition. This is the usual idiom for checking whether a string is empty.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204