Reputation: 4466
Have a shell script which, in turn, run a java program. The script is invoked as follows :
./script.sh 1 2 3 4 "ab cd"
The 5th shell argument (ab cd) must be passed as a a java system property, what I'm doing is this :
JAVA_OPTS="-Xmx512M -Dlog4j.defaultInitOverride=true"
if [ "$5" ] ; then
JAVA_OPTS="$JAVA_OPTS -Dconfig.path=$5"
fi
Then, run java (JAVA_EXE & CP have proper values) :
$JAVA_EXE $JAVA_OPTS -classpath $CP com.foo.Main
Receiving this error :
Error: Could not find or load main class cd
If passing "abcd" instead of "ab cd" everything is ok.
If passing inline, just surround the value with quotes :
java -Xmx512M -Dconfig.path="ab cd" com.foo.Main
The problem occurs when a variable must be used.
How should I pass the argument containing spaces correctly ?
Upvotes: 3
Views: 2090
Reputation: 183241
Instead of building JAVA_OPTS
as a string, you can build it as an array:
JAVA_OPTS=(-Xmx512M -Dlog4j.defaultInitOverride=true)
if [ "$5" ] ; then
JAVA_OPTS+=("-Dconfig.path=$5")
fi
"$JAVA_EXE" "${JAVA_OPTS[@]}" -classpath "$CP" com.foo.Main
(Note: the Bourne shell did not have arrays, and POSIX does not require shells to support them, so this approach is not maximally portable. If you use this approach, make sure the first line of your script is something like #!/bin/bash
or #!/bin/zsh
and not something like #!/bin/sh
.)
Upvotes: 7
Reputation: 4466
The only solution I found is to use a special variable for the problematic param
CONFIG_PATH="-Da=a"
if [ "$5" ] ; then
CONFIG_PATH=-Dconfig.path=$5
fi
$JAVA_EXE $JAVA_OPTS "$CONFIG_PATH" -classpath $CP com.foo.Main
It must have some value, otherwise the empty value will be taken as the name of the main class.
Upvotes: 1
Reputation: 4861
$JAVA_EXE $JAVA_OPTS -classpath $CP com.foo.Main
MUST be $JAVA_EXE "$JAVA_OPTS" -classpath $CP com.foo.Main
- Pay attention to the double quotes around $CP
EDIT: JAVA_OPTS="$JAVA_OPTS -Dconfig.path=$5"
should also be JAVA_OPTS="$JAVA_OPTS -Dconfig.path='"'$5'"'"
Upvotes: 0