Reputation: 1499
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
Upvotes: 3
Views: 1688
Reputation: 6365
Pidof:
x=`pidof firefox`
if [[ $x > 0 ]];
then
kill -9 $x
echo "Firefox terminated"
else
echo "bla bla bla"
fi
Upvotes: 0
Reputation: 185073
What about :
pkill &>/dev/null firefox && echo "ff terminated" || echo "no ff PIDs"
No need -9
signal here ;)
Upvotes: 1
Reputation: 1631
if x=$(pgrep firefox); then
kill -9 $x
# ...
fi
If you just want to kill the process:
pkill -9 firefox
Upvotes: 3
Reputation: 20315
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.
Upvotes: 2