Cannot launch shell script with arguments using Java ProcessBuilder

DigitalDyn picture DigitalDyn · Aug 14, 2013 · Viewed 13.4k times · Source

I am trying to execute a shell script with command line arguments using ProcessBuilder, this shell script inturn calls two other shell scripts that uses this argument. The first shell script runs fine, but when the second one is started it returns exit code 1.

ProcessBuilder snippet from Java Program:

//scenario - A string that holds a numerical value like 1 or 2 etc
String[] command2 = {"/bin/bash", "<path to shell script>/runTemporaryTestSuite.sh", scenario};
ProcessBuilder pb2 = new ProcessBuilder(command2);
Process p2 = pb2.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line;
//print - is an object ref of response.getWriter() //
print.println("Output of running "+Arrays.toString(command2)+" is: ");
while ((line = br.readLine()) != null) {
    print.println(line);
}

try {
   int exitValue = p2.waitFor();
   print.println("<br><br>Exit Value of p2 is " + exitValue);
} catch (InterruptedException e) {
   e.printStackTrace();
}

runTemporaryTestSuite.sh

#!/bin/bash
sh <path to script>/clearRegressionResult.sh   (This runs fine)
sh <path to script>/startRegression.sh $1 (This is where the issue occurs)

startRegression.sh looks like:

SUITE_PATH="./"
java -DconfigPath=${SUITE_PATH}/config.xml -Dscenario=$1 -Dauto=true -jar test.jar

My output: Output of running [/bin/bash, /runTemporaryTestSuite.sh, 29] is: Exit Value of p2 is 1

Any help in resolving this is really appreciated.

Answer

drgn picture drgn · Aug 14, 2013

In think the problem is not that you cannot launch shell script with arguments, I was curious and I did a test

public class Main {

public static void main(String[] args) throws IOException {
    String[] command = {"/bin/bash", "test.sh", "Argument1"};
    ProcessBuilder p = new ProcessBuilder(command);
    Process p2 = p.start();
    BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
    String line;

    System.out.println("Output of running " + command + " is: ");
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

here is the test.sh script

echo Hello im the script, here your args $@

Here the output

Output of running [Ljava.lang.String;@604e9f7f is: 
Hello im the script, here your args Argument1

What I think is just that your startRegression.sh exit with a non-0 status (aka it failed somewhere) and it have repercussion, runTemporaryTestSuite.sh will also exit with a non-zero status, and so on hence the message : Exit Value of p2 is 1

What I see right now,

SUITE_PATH="./" java -DconfigPath=${SUITE_PATH}/config.xml [..] the configPath will be .//config.xml so maybe you have a plain file not found issue? I might be wrong, hope it helped