1

I know there are a lot of post about executing commands from Java but I just can't get this to work. Here is what I'm trying to do, I have a bash script, it receives 2 arguments which might or might not have spaces, then from Java I'm executing the script and passing the arguments like this(I'm surrounding the arguments with quotes and escaping them with backslashes):

String cmd = "/opt/myScript  \"/opt/myPath1\"  \"/opt/myPath2 with spaces\"";
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);

I also tried to use the ProcessBuilder class like this:

String myScript = "/opt/myScript";
String myArg1= "/opt/myPath1";
String myArg2 = "/opt/myPath2 with spaces";
ProcessBuilder pb = new ProcessBuilder(myScript , myArg1, myArg2);
pb.start;

Arguments with no spaces are received successfully but I still have problems with the second one.

I thought the ProcessBuilder class would handle the spaces but seems like I'm missing something.

I'm not sure if it has something to do, but just in case here is my script:

#!/bin/bash
PATH=$PATH:$1
gnome-terminal --working-directory $2

$1 and $2 are the arguments sent from Java.

CIOC
  • 1,385
  • 3
  • 19
  • 48
  • 1
    What problem are you having? What values does your script receive with the `ProcessBuilder`? – Elliott Frisch Jul 29 '15 at 23:43
  • You need to quote the expansion of the variables in the shell script too. Otherwise the shell will word split on the spaces. (Technically, it won't do this on the assignment line but quoting there is safer if you want to be extra sure.) – Etan Reisner Jul 29 '15 at 23:44
  • Possibly duplicate of http://stackoverflow.com/questions/17141767/having-spaces-in-runtime-getruntime-exec-with-2-executables – Felipe Arenales Jul 30 '15 at 03:28
  • @Elliott, it works now, I just surrounded both variables `$1` and `$2` with quotes, I guess it will work on Mac too, thanks. – CIOC Jul 30 '15 at 04:57

2 Answers2

2

Get the same trouble, finally solved with:

Runtime.getRuntime().exec(new String[]{"bash", "-c", <command with spaces>});
Tou Hat
  • 49
  • 5
0

Runtime.exec() is an overloaded method. There are several possible ways how to call it. The call exec(String command) executes the specified string command but the argument are separated by spaces here. The method exec(String[] cmdarray) executes the specified command and arguments. There are other exec() variants but the best for you is

String cmd[] = new String[] {"/opt/myScript", "/opt/myPath1", "/opt/myPath2 with spaces" };
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);

It is possible to use ProcessBuilder can be used as well for argument passing. I think the only error is missing parenthesis after pb.start.

And last but not least the script has a major bug. It does not contain quutes arround $2. It should be

#!/bin/bash
PATH="$PATH:$1"
gnome-terminal --working-directory "$2"
Zaboj Campula
  • 3,155
  • 3
  • 24
  • 42