Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am using

ps -ef | grep java | wc -l

to find the number of java processes running at any given time.

The above command obviously counts the "ps -ef | grep java" command also in the result.

To avoid this, I found out that I could use

ps -ef | grep [j]ava | wc -l

and it works fine. However, I would like to figure out the reason why it is able to skip the original command from the results.

share|improve this question
    
By the way. try running 'ps -ef | grep -c [j]ava' –  Oesor Jun 17 '09 at 11:59
add comment

7 Answers 7

Because when you grep for [j]ava, the process is named 'grep [j]ava'. '[j]ava' doesn't match the regex '[j]ava', and thus doesn't show up in the results.

share|improve this answer
add comment

When you do this:

ps -ef | grep [j]ava | wc -l

you are using the pattern [j]ava which matches any single character between the square brackets (which consists only of the single letter j) followed immediately by the characters ava. The grep process itself does not contain the letter j followed immediately by the letters ava, but instead contains a square bracket, then j, then a closing square bracket, then ava.

That is, the pattern does not match itself.

share|improve this answer
add comment

This isn't exactly an answer to your question, but...

Another common way to accomplish the same thing is:

ps -ef|grep java|grep -v grep|wc -l

This of course works by doing an inverted grep on the term grep itself

share|improve this answer
add comment

You've changed the name of the grep process, so that it no longer contains the term "java"

share|improve this answer
add comment

To go along with other answers to hopefully help clarify:

grep java matches anything that has java within it.

grep java
java

grep [j]ava matches explicitly "java":

grep [j]ava <- There is no string "java" here so it does not match
java

share|improve this answer
add comment

use the pgrep command?

share|improve this answer
    
I think the pgrep command is not universal across all unix platforms –  ericslaw Jun 18 '09 at 9:55
    
I know from experience it works on solaris and linux. Don't know about BSDs or other proprietary unices. –  Jason Tan Jun 18 '09 at 17:16
add comment

starting with JDK 1.5, you have the jps (linux /usr/lib/jvm/java-6-sun/bin/jps). You can use it on all the operating system (linux, windows, solaris)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.