Tuesday, July 19, 2011

ps oneliner: search for a specific running process

Have you ever wanted to verify/search for a running process? Or, have you ever wanted to see if you had multiple counts of the same process, possibly indicating orphans or hung processes?

It's rather easy! As an example, assuming you are logged in as root or su'd, and looking for snort:

ps -ef | grep -v grep | grep snort

The "grep -v grep" command will invert the selection for lines matching "grep"....so it will print ONLY lines that do not contain "grep". Why is this important? Well...it's not. However, the grep command is a process itself so if you have one running snort process, you will get two lines returned:
- the line containing the actual results for the real snort process
- the line containing the grep action(s)

So, assuming that you have only snort running, and running only once, this command would return one line, showing the snort process information (including startup arguments...yay!)

But what if you need to count how many processes? Add the -c switch to the final pipe to grep:

ps -ef | grep -v grep | grep -c snort

This will return an integer value of the number of processes containing snort in the return of the ps command.
It's important to note that this DOES count/show EVERY line of the ps output that contains "snort". This could, if you were running other programs that integrated with snort parts, such as Barnyard, count/show more than one line.

 There is a lot more fun that could be had with this. For example, you could search for more than one process, use awk to strip their PIDs, and then find the difference of the two....a quick way to see if one of a group of automatically started programs might be have hung after the other one(s) restarted.

Don't forget these helpful notes too:
grep -i     ...case-insensitive
||              ...logical OR operator...look for this OR that
&&          ...logical AND operator....must match BOTH
     --cat filename1 | grep something1 | grep something2     ...is inherently a logical AND operation


  1. Hey Dave,

    I've been enjoying your bash fu recently!

    Here's an alternative to the "grep -v grep".

    Change this:
    ps -ef | grep -v grep | grep snort

    to this:
    ps -ef |grep snor[t]

    The modified grep still succeeds in showing only those lines that include "snort" but it no longer matches its own search criteria so doesn't get included in the results.

    Keep up the good work!

    Doug Burks

  2. Hey Doug! Thank you for the comment. Sometimes I forget that people actually read this thing. :-) You are definitely right about the brackets. I just never got in the habit of using them and have just used the -v option. The next few times I need to run the ps, I am definitely going to use the brackets. Still have more to learn/remember I guess. :-)