1

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.

1
  • By the way. try running 'ps -ef | grep -c [j]ava'
    – Oesor
    Jun 17, 2009 at 11:59

7 Answers 7

10

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.

3

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.

2

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

1

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

1

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

1

use the pgrep command?

2
  • I think the pgrep command is not universal across all unix platforms
    – ericslaw
    Jun 18, 2009 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, 2009 at 17:16
0

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)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .