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 🙂
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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
Method 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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0