-3

Using Java's runtime.exec(cmd) to run a perl string on HP-UX unix then getting the error

Can't find string terminator "'" anywhere before EOF at -e line 1.

The perl script I'm testing with is:

perl -e 'print "Hello World \n"'

It works from the Unix command line. Tried a number of escape variations and tried using qq, like perl -e 'print qq{Hello World \n}' without success.

Any other suggestions?

Thanks

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

1

When you use Runtime.exec(String command), "the string is parsed using white space as the delimiter". That means that

perl -e 'print "Hello World\n"'

tells Java to execute the following:

program: perl
1st arg: -e
2nd arg: 'print
3rd arg: "Hello
4th arg: World\n"'

The arg after -e ('print) is the Perl code to execute. This is obviously incorrect. You want to execute the following:

program: perl
1st arg: -e
2nd arg: print "Hello World\n"

You can achieve that or equivalent using exec(String[] cmdarray).

Runtime.getRuntime().exec(
   new String[] {
      "perl",
      "-e",
      "print \"Hello World\\n\""
   }
);

Or you could invoke a shell to parse the command for you:

Runtime.getRuntime().exec(
   new String[] {
      "sh",
      "-c",
      "perl -e 'print \"Hello World\\n\"'
   }
);
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Since the OP is exec'ing the command in Java, I don't believe a shell is ever invoked...see my comment on the answer. (I'm not a Java expert so I could be wrong) – ThisSuitIsBlackNot Oct 16 '13 at 18:33
  • 1
    From the article [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=1): "If you use the version of exec() with a single string for both the program and its arguments, note that the string is parsed using white space as the delimiter via the StringTokenizer class." So it looks like you were almost spot on, except that there would only be 3 args instead of 4. – ThisSuitIsBlackNot Oct 16 '13 at 18:56
  • My answer was close, but as @ThisSuitIsBlackNot points out, it was actually quite flawed. Fixed. – ikegami Oct 16 '13 at 19:19
  • Just realized that my comment about 3 args instead of 4 was wrong, as your updated answer shows. From now on I'll leave argument parsing to the machines :P – ThisSuitIsBlackNot Oct 16 '13 at 19:33