CIOC
CIOC

Reputation: 1427

Execute bash script and pass arguments with spaces from java

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.

Upvotes: 1

Views: 3094

Answers (2)

Tou Hat
Tou Hat

Reputation: 59

Get the same trouble, finally solved with:

Runtime.getRuntime().exec(new String[]{"bash", "-c", <command with spaces>});

Upvotes: 2

Zaboj Campula
Zaboj Campula

Reputation: 3360

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"

Upvotes: 0

Related Questions