Take the 2-minute tour ×

I want to parse the output of the ps command and return true or false if a program is found. How would anyone here do this? I have access to the command line so it's open for me, no restrictions.

share|improve this question

migrated from stackoverflow.com Jan 11 '10 at 2:59

This question came from our site for professional and enthusiast programmers.

I originally thought this should be moved to superuser.com and voted as such, but the OP wants it in a shell script so stackoverflow.com is appropriate for it. –  LeakyCode Jan 10 '10 at 17:10

5 Answers 5

Pipe the output to grep.

ps -ax | grep process_name | grep -v grep

The above is more suited for causally checking stuff by hand. If you want to use something in a script, use the return value from pidof:

pidof process_name

returns 0 if some process exists with the specified name and 1 otherwise.

share|improve this answer
Yeah but that won't return a value. I need to have something return true if found. –  Jim Jan 10 '10 at 17:02
Or, use if ps -ax | grep [p]rocess_name; then whatever; fi. –  Alok Jan 10 '10 at 17:03
Jim: if you want to use it in a script, use pidof process_name. –  LeakyCode Jan 10 '10 at 17:04
Thanks Mehrdad, pidof is what I needed. –  Jim Jan 10 '10 at 17:09

Use pgrep, as in pgrep pattern.

share|improve this answer

In the general case, you should look for your SPECIFIC process in the process list, rather than something which just happens to have the same name.

We've previously been bitten by bugs where a process with the same (or similar) name appears and breaks something (usually a monitor or start/stop script, so it's not usually vital).

Your process should write a pid file when it starts up (or before, by having a shell script write its pid in then exec your task), and then you can refer to the contents of that pid file in a subsequent shell script.

To check if a specific pid is running, kill it with "signal 0" - this doesn't actually send a signal just checks that it is there.

share|improve this answer

I wouldn't recommend the ps and pipe through grep approach in the other answer reason being that you might get false positives (especially for short command names which are abundant in UNIX) and have to resort to double greps etc. just to figure it out. Instead, consider using the -C option of ps to print the pid of the process you're concerned with.

The best approach though would be to maintain the pid of the process you've spawned off in a file or in the memory of the controller process so that you know it upfront and can search for it.

share|improve this answer

use if pgrep APPLICATION > /dev/null then dox; fi

share|improve this answer

Your Answer

