Find the process id of a java application in a bash script (to see if the target application is already running)
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
Related videos on Youtube
Jarek
You may be interested in the story of SE moderator Monica Cellio and how she was unfairly treated by the corporate management of this site. More info here. An update is available. Let's hope we can cultivate a more fair environment for content creators and moderators going forward.
Updated on September 18, 2022Comments
-
Jarek over 1 year
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.)
-
Jarek almost 11 yearsThanks. It works and it is very easy to use (and remember).