Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 419
Chris Redford Avatar asked Nov 30 '09 19:11

Chris Redford


People also ask

How do I check if a process is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

How do I see what processes are running in Terminal Mac?

Launch Terminal (Finder > Applications > Utilities). When Terminal is running, type top and hit Return. This will pull up a list of all your currently running processes. As in the Activity Monitor, this list shows your processes in decreasing order of how much of your resources they're consuming.

How do I find the PID of a process Mac?

Run the command lsof -i : (make sure to insert your port number) to find out what is running on this port. Copy the Process ID (PID) from the Terminal output.


1 Answers

Parsing this:

ps aux | grep -v grep | grep -c [-i] $ProcessName 

...is probably your best bet.

ps aux lists all the currently running processes including the Bash script itself which is parsed out by grep -v grep with advice from Jacob (in comments) and grep -c [-i] $ProcessName returns the optionally case-insensitive integer number of processes with integer return suggested by Sebastian.

Here's a short script that does what you're after:

#!/bin/bash PROCESS=myapp number=$(ps aux | grep -v grep | grep -ci $PROCESS)  if [ $number -gt 0 ]     then         echo Running; fi 

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.

like image 176
Jed Smith Avatar answered Sep 20 '22 18:09

Jed Smith