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

I am trying to check if a particular process is working, and if so, try to kill it.

I got the following:

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 in unix silently?

0
source share
3 answers
 [ -z $PID] 

true if $PID empty, and not vice versa, so your test is inverted.

You should use pgrep if you have it on your system. (Or even better: pkill and stop worrying about all this shell logic.)

+5
source

The answer is simpler.
The killall program is part of almost every distribution.

Examples:

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

Now there is also "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, when you used "ps" in your example, here is the best way to use it without requiring "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 of the above methods are better than imho long pipe

+5
source

Try if [ X$PID != X ] in your state. This is a common idiom to check if a string is empty.

-1
source

All Articles