简体   繁体   中英

Pass shell script argument containing spaces as java system property

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 aa 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 ?

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 .)

$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'"'"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM