1

I am doing a simple job of passing my java arguments from shell to java and one of the arguments happen to have spaces.

./test.ksh -test param1 param2 "\"param3 with spaces\""

code in test.ksh

if [ "$1" = "-test" ]
then
   echo "Test"
   SCRIPT_ARG="${*}"
   echo "${SCRIPT_ARG}"
fi

java -jar test.jar ${SCRIPT_ARG}

But inside the java code the third parameter is being read and printed as

"param3

it seems very simple, but short of ideas here

user1933888
  • 2,897
  • 3
  • 27
  • 36
  • I have no problems passing strings with spaces directly to java: `java "abc def" "ghi"` – David Choweller Dec 05 '16 at 22:47
  • 1
    This is actually trickier than it looks, but it's answered here (NOT the accepted answer; look at the second or other answers): http://stackoverflow.com/a/8723305/719547 – Jim Stewart Dec 05 '16 at 22:49
  • Try `java -jar test.jar "param with spaces"` Or just enclose ${SCRIPT_ARG} in spaces: `java -jar test.jar "${SCRIPT_ARG}"` – David Choweller Dec 05 '16 at 22:57

1 Answers1

1

Arguments are a list of strings, but you concatenate them into a single string that you then re-split on spaces.

Instead, don't concatenate them and instead process them as a list of strings:

#!/usr/bin/ksh

if [ "$1" = "-test" ]
then
   echo "Test"
   script_arg=( "${@}" )
   for i in "${script_arg[@]}"
   do
     echo "One of the arguments is: $i"
   done
fi

java -jar test.jar "${script_arg[@]}"

You should then run it with:

./test.ksh -test param1 param2 "param3 with spaces"

and not try to embed any more quotes.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • You need to shift the `-test` arg off. – Jim Stewart Dec 05 '16 at 22:51
  • OP doesn't do or mention that, but maybe. – that other guy Dec 05 '16 at 22:52
  • You're right, but I think OP meant that too. Anyway, see the dup link in my question comment; this is one of the answers there too. – Jim Stewart Dec 05 '16 at 22:53
  • Thanks for your response, so the key was "${script_arg[@]}", including each param in quotes at this point. if I pass quotes in quotes (with escaping) why does java does not accept it as a quotes argument? – user1933888 Dec 05 '16 at 23:05
  • 1
    Quotes are shell syntax that ksh uses to fill in your Java program's `String[] args`. Java doesn't know about or interpret quotes. If you call `main(new String[] { "foo", "\"bar", "baz\"" })` you'd obviously also see 3 elements in the array, and not 2. The literal quotes don't matter and aren't reinterpreted. – that other guy Dec 05 '16 at 23:09
  • @thatotherguy" makes perfect sense..thanks!..god bless you – user1933888 Dec 05 '16 at 23:12