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?

3
  • 3
    Are you sure you wanted -z? -n seems more likely, if [[ -n $PID ]]. Commented Feb 22, 2012 at 20:26
  • does this work?: kill -s 9 $PID > /dev/null Commented Feb 22, 2012 at 20:39
  • 2
    Tangentially, ITYM ps aux | awk '/[m]yprocessname/{print $2}'. See also partmaps.org/era/unix/award.html Commented Feb 22, 2012 at 20:40

3 Answers 3

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.)

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

pkill is however not equal to killall; the former does a substring regex grep, which can be... potentially dangerous.
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.