I want to write in a bash script a piece of code that checks if a program is already running. I have the following in order to search whether bar is running
Why ask ps to provide massive amounts of output with -ef if you only are going to throw away 99% of it? ps and especially the GNU version is a swiss army knife of handy functionality. Try this:
ps -C bar -o pid= 1>/dev/null
I specify -o pid= here just because, but in fact it's pointless since we throw away all of stdout anyway. It would be useful if you wanted to know the actual running PID, though.
ps automatically will return with a non-zero exist status if -C fails to match anything and with zero if it matches. So you could simply say this
ps -C bar 1>/dev/null && echo bar running || echo bar not running
Or
if ps -C bar 1>/dev/null ; then
echo bar running
else
echo bar not running
fi
Isn't that simpler? No need for grep, not twice or even once.