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.

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

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.


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.


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


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


To go along with other answers to hopefully help clarify:

grep java matches anything that has java within it.

grep java

grep [j]ava matches explicitly "java":

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


use the pgrep command?

  • 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

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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