java - 无法使用 Java ProcessBuilder 启动带有参数的 shell 脚本

标签 java shell processbuilder exit-code

我正在尝试使用 ProcessBuilder 执行带有命令行参数的 shell 脚本,此 shell 脚本依次调用使用此参数的另外两个 shell 脚本。第一个 shell 脚本运行良好,但是当第二个 shell 脚本启动时它返回退出代码 1。

Java 程序中的 ProcessBuilder 片段:

//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();
}

运行临时测试套件.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 看起来像:

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

我的输出: 运行 [/bin/bash,/runTemporaryTestSuite.sh, 29] 的输出是: p2的退出值为1

非常感谢您提供解决此问题的任何帮助。

最佳答案

我认为问题不在于你不能用参数启动 shell 脚本,我很好奇,我做了一个测试

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);
    }
}

这里是test.sh脚本

echo Hello im the script, here your args $@

这里是输出

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

我认为只是你的 startRegression.sh 以非 0 状态退出(又名它在某处失败)并且它有影响,runTemporaryTestSuite.sh 也将以非零状态退出,等等因此消息: p2的退出值为1

我现在看到的,

SUITE_PATH="./" java -DconfigPath=${SUITE_PATH}/config.xml [..] configPath 将是 .//config.xml 所以也许您遇到了未找到普通文件的问题?我可能是错的,希望它有帮助

关于java - 无法使用 Java ProcessBuilder 启动带有参数的 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18240944/

相关文章:

java - 除非插入 Toast 行,否则应用程序中的奇怪行为不会播放声音

linux - 从下面的 Shell 脚本中查找哪个文件有问题

linux - 如何在 Linux 中将每天的文件分成几小时

bash - Shell:捕获变量中的输出文件

java - Processbuilder 在执行批处理脚本时挂起

java - 类对象的通用类型规范

java - Android 从 URI 读取文本文件

java - 在java中复制多个文件

java - ProcessBuilder 在同一项目中启动主要方法

java - 在Java中执行未知的Python脚本