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.)
Best Answer
By default,
pgrep
only matches the command, not the arguements. To match the full command line, you need the-f
option.From the pgrep manpage: