Pass shell script argument containing spaces as java system property
java, shell
Solution
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`.)
Problem
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 ?