I am writing a shell script to build Java options dynamically in a variable array and pass them to java.exe. If an option value contains a space, I cannot find a way to get it interpreted correctly. Here is my example:
#!/bin/bash
JAVA_HOME=/opt/jvm/jre1.5.0_18
JAVA_OPTS=("-Xms256m -Xmx256m")
JAVA_OPTS=("${JAVA_OPTS[@]}" "-Dthis.is.a.test=\"A B C\"");
# ... and so on ...
echo ${JAVA_OPTS[@]}
$JAVA_HOME/bin/java ${JAVA_OPTS[@]} some.java.class
Although JAVA_OPTS echoes correctly as
-Xms512m -Xmx512m -Dthis.is.a.test="A B C"
Java does not consider the quotes and complains:
Exception in thread "main" java.lang.NoClassDefFoundError: B
I tried with and without escaping, with single and double quotes and a couple other fancy variations, without success. Any help is welcome.
That's a problem. JAVA_OPTS will not change and bash will try to find and execute an executable by the name of -Dthis.is...
Though the basically, you're trying to put all the options into one string instead of into an array of strings. That's reasonable as long as no option has a space. Then it would be used like this, with NO QUOTES when used.
Thank you both for your replies. Actually I had tried a version with String variable instead of Array. The exact syntaxt for it should be:
#!/bin/bash
JAVA_HOME=/opt/jvm/jre1.5.0_18
JAVA_OPTS="-Xms512m -Xmx512m"
JAVA_OPTS="$JAVA_OPTS -Dthis.is.a.test=\"A B C\""
# ... and so on ...
echo ${JAVA_OPTS}
$JAVA_HOME/bin/java ${JAVA_OPTS} some.java.class
But this leads to the exact same result:
Exception in thread "main" java.lang.NoClassDefFoundError: B
The interpreter is not considering the " in "A B C".