Check if process is running Mac OS X then execute code
11,610
Solution 1
As @StéphaneChazelas mentions, you can use pgrep
- from the man page:
The pgrep command searches the process table on the running system and prints the process IDs of all processes that match the criteria given on the command line.
SERVICE='Google Chrome'
if pgrep -xq -- "${SERVICE}"; then
echo running
else
echo not running
fi
Solution 2
You need to quote "$SERVICE":
SERVICE='Google Chrome'
if ps ax | grep -v grep | grep "${SERVICE}" &> /dev/null; then
echo running
else
echo not running
fi
Related videos on Youtube
Author by
Ryan Hawdon
Updated on September 18, 2022Comments
-
Ryan Hawdon almost 2 years
I am creating a script which clears the cache for Google Chrome. However, I would like to check if Chrome is open and if so not run the code but if it isn't then it will execute the code. I can see that the Process Name is Google Chrome but the code doesn't work.
This is what I have done so far. What am I doing wrong?
SERVICE='Google Chrome' if ps ax | grep -v grep | grep $SERVICE then RUNS THE CODE else echo "PLEASE CLOSE GOOGLE CHROME" fi
Any help would be appreciated :)
-
Stéphane Chazelas almost 9 yearsOr just
pgrep -f "$SERVICE"
. Note that it would return true as long as there's a process that hasGoogle Chrome
in its argument list, so is not fool-proof and generally not the right way to check that a service is running. -
Digital Trauma almost 9 years@StéphaneChazelas why specify the
-f
at all? -f Match against full argument lists. The default is to match against process names. Without the-f
I think we just match against process name which is what is needed here, right? -
Stéphane Chazelas almost 9 yearsOr
pgrep -xq -- "$SERVICE"
. Note that not allpgrep
implementations support-q
. -
Digital Trauma almost 9 years@StéphaneChazelas Yes,
-x
is nicer. I'm assuming the OSXpgrep
, since that is how the question was tagged.