Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative bash script to check if a process is running

Tags:

bash

What would be the easiest and the most reliable way to check if a process is running in a script using bash?

Here´s what i have:

x=`ps aux | grep firefox | grep -v grep | awk '{print $2 }'`

if [ $x > 0 ];
then kill -9 $x
echo "Firefox terminated"
else echo "bla bla bla"
fi
like image 946
Dynamiite Avatar asked Dec 05 '25 17:12

Dynamiite


2 Answers

if x=$(pgrep firefox); then
    kill -9 $x
    # ...
fi

If you just want to kill the process:

pkill -9 firefox
like image 122
tlo Avatar answered Dec 08 '25 08:12

tlo


Maybe you can use pgrep to do this ?

From the man page:

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria to stdout.

Example:

$> pgrep firefox | xargs -r kill -9

In this example, the pid of the process is used by the kill command. The -r option of xargs allows to execute the kill command only if there is a pid.

like image 29
julienc Avatar answered Dec 08 '25 06:12

julienc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!