Alternative bash script to check if a process is running

What would be the simplest and most reliable way to check if a process in a script is running 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

      

+3


source to share


4 answers


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

      

If you just want to kill the process:



pkill -9 firefox

      

+3


source


Perhaps you can use it pgrep

for this?

From the man page :

pgrep looks at the currently running processes and lists the process IDs that match the selection criteria for stdout.



Example:

$> pgrep firefox | xargs -r kill -9

      

In this example, the pid of the process is used by the command kill

. The option -r

xargs

allows to execute the command kill

only if pid is present.

+2


source


What about:

pkill &>/dev/null firefox && echo "ff terminated" || echo "no ff PIDs"

      

No -9

signal needed here;)

+1


source


Pidof:

x=`pidof firefox`
if [[ $x > 0 ]];
then
kill -9 $x
echo "Firefox terminated"
else
echo "bla bla bla"
fi

      

0


source







All Articles