I know there are a million questions on getting the process ID, but this one seems to be unique. Google has not given me the answer, so I hope stackexhange will help rather than close this question.

When Java is involved it seems trickier to find a process ID (pgrep doesn't work afaik).

Furthermore, I need to automate this in a bash script. One issue I've encountered is that when I use ps aux | grep the grep process itself always shows up, so handling the results in a simple bash script is not trivial enough for me to figure out a good solution on my own (with my limited bash skills).

Some things I have tried:

Example 1 - this returns a process even though there is no application by that name:

$ ps aux | grep -i anythingnotreal
user2   3040  0.0  0.0   4640   856 pts/3    S+   18:17   0:00 grep --color=auto -i anythingnotreal

Example 2 - this returns nothing even though "java_app" is currently running:

$ pgrep java_app

It returns nothing. However, here's proof that "java_app" is running:

$ ps aux | grep java_app
tester2   2880  0.7  2.8 733196 58444 ?        Sl   18:02   0:07 java -jar /opt/java_app2/my_java_app.jar
tester2   3058  0.0  0.0   4644   844 pts/3    S+   18:19   0:00 grep --color=auto java_app

What I need is a solution I can plug into a bash script that will tell me if the java application of interest (for which I know the jar file name and path) is currently running. (If it is running, I need to ask the user to close it before my script continues.)


By default, pgrep only matches the command, not the arguements. To match the full command line, you need the -f option.

$ pgrep -f java_app

From the pgrep manpage:

-f The pattern is normally only matched against the process name. When -f is set, the full command line is used

  • Thanks. It works and it is very easy to use (and remember). – MountainX Jun 29 '13 at 23:15

You can use pidof java to figure out what java processes are running and then get the detail of each process such as ps -p $PID -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS, then you can determine if target application is running and it usage whether need to ask user to close or continue.


You can use jcmd utility that's part of the JDK. It only lists currently running Java processes, so all you need to do is grep for java_app

jcmd | grep java_app | cut -d " " -f 1

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.