Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass shell script argument containing spaces as java system property

Tags:

java

shell

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 ?

like image 913
Bax Avatar asked Jul 16 '26 21:07

Bax


1 Answers

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

like image 183
ruakh Avatar answered Jul 19 '26 09:07

ruakh