bash - statement - shell script check if process is running
Why “if $(ps aux | grep …)” always succeeds in Bash? (4)
grep process itself is being returned by
ps. You can "trick"
grep to not match itself by surrounding one of the search characters in a character class
[ ] which doesn't change the functionality:
if ps aux | grep -q "[b]la bla" ; then echo "found" ; fi
Also, the use of process substitution
$() is unnecessary. The
if will work on the success of the last command in the pipe chain, which is what you want.
Note: The reason the character class trick works is because the
ps output still has the character class brackets but when
grep is processing the search string, it uses the brackets as syntax rather than a fixed string to match.
Why the following
if statement succeeds ?
if $(ps aux | grep -q "bla bla") ; then echo "found" ; fi
If you grep the output from
ps aux, you will always get a process showing your previous command. To fix this, you can pipe the output to grep twice, once to remove line with "grep" in it, and again for the process your looking for.
ps aux | grep -v "grep" | grep "Finder"
You need to filter out the process that is
grepping for 'bla bla':
$ if ps aux | grep -v 'grep' | grep -q 'bla bla'; then echo 'Found' fi
the 'grep' process is already running by the time ps runs, so the ps output includes it.
pgrep is precisely for this purpose:
if pgrep "bla bla" ; then echo "found" ; fi