Check if Mac process is running using Bash by process name


How do you check if a process on Mac OS X is running using the process's name in a Bash script?

I am trying to write a Bash script that will restart a process if it has stopped but do nothing if it is still running.

2/25/2014 3:38:19 PM

Accepted Answer

Parsing this:

ps aux | grep [-i] $ProcessName | wc -l probably your best bet. Here's a short script that does what you're after:

number=$(ps aux | grep $PROCESS | wc -l)

if [ $number -gt 0 ]
        echo Running;

EDIT: I initially included a -i flag to grep to make it case insensitive; I did this because the example program I tried was python, which on Mac OS X runs as Python -- if you know your application's case exactly, the -i is not necessary.

The advantage of this approach is that it scales with you -- in the future, if you need to make sure, say, five instances of your application are running, you're already counting. The only caveat is if another application has your program's name in its command line, it might come up -- regular expressions to grep will resolve that issue, if you're crafty (and run into this).

Research the Darwin man pages for ps, grep, and wc.

11/30/2009 7:47:45 PM

A shorter solution:

if pgrep $PROCESS_NAME; then
    echo 'Running';


pgrep exits with 0 if there is a process matching $PROCESS_NAME running, otherwise it exist with 1.
if checks the exit code of pgrep, and, as far as exit codes go, 0 is success.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow