5

I am completely new to Windows batch programming. What I want to achieve is to write a startup script for a Java application. Yet, it does not start the Java application, but rather prints out

Usage: java [-options] class [args...]

(to execute a class)

or java [-options] -jar jarfile [args...]

(to execute a jar file)

...

which indicates that my parameters are not correctly recognized.


Here is my MCVE for the not-working script:

set memory=600000
java -XX:OnOutOfMemoryError="taskkill /PID %p" -Xmx%memory%K -jar MyApp.jar

In the real scenario, memory is calculated to set the optimal maximal heap size for the application.


Leaving out one of both parameters makes the app start. So

java -XX:OnOutOfMemoryError="taskkill /PID %p" -jar MyApp.jar

and

set memory=600000
java -Xmx%memory%K -jar MyApp.jar

works, but I need both parameters to work in one call.

Community
  • 1
  • 1
Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
  • Try putting `@echo on`/`@echo off` in your script ([described here](http://stackoverflow.com/a/10237457/3788176)) and see what command it is actually executing in the "both parameters" case. – Andy Turner Mar 14 '16 at 14:15
  • Thanks for the input! Using `@echo on` results in printing `java -XX:OnOutOfMemoryError="taskkill /PID memoryK -jar MyApp.jar`, which indicates some mistake with the `"`, which is not closed anymore, and the parameter, which is not added (`%memory%)`... – Markus Weninger Mar 14 '16 at 14:17
  • 2
    What it looks like is happening there is the `%` in `%p` is considered an "opening" `%` for substitution - I think that `%%` is the token for a single `%` (like in `printf`-like methods). – Andy Turner Mar 14 '16 at 14:18

1 Answers1

2

If you put @echo on and @echo off in your script you can see what command is actually being executed.

You say that the resulting command is:

java -XX:OnOutOfMemoryError="taskkill /PID memoryK -jar MyApp.jar

which makes it look like the % of %p is being considered an "opening" % for the substitution.

Aside from the quotes not being balanced, this means that you are effectively not giving java a command to run - the -jar MyApp.jar is actually inside the -XX:OnOutOfMemoryError string.

Try replacing the single % with %% - according to this question, that is how to write a literal % in a BAT file:

java -XX:OnOutOfMemoryError="taskkill /PID %%p" -Xmx%memory%K -jar MyApp.jar
Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243