在ProcessBuilder中添加双引号符号

时间:2017-07-23 00:10:13

标签: java bash shell

我正在使用ProcessBuilder来构建我的命令。我想在这篇文章之后建立我的命令:How do I launch a java process that has the standard bash shell environment?

即,我的命令是这样的: /bin/bash -l -c "my program"

但是,我很难将双引号传递到ProcessBuilder,因为new ProcessBuilder(List<String> command)如果我原生地将双引号添加到List<String> command,则无法对命令进行短语。 ProcessBuilder将双引号视为参数。

相关代码:

    //Construct the argument
    csi.add("/bin/bash");
    csi.add("-l");
    csi.add("-c");
    csi.add("\"");
    csi.add(csi_path);
    csi.add(pre_hash);
    csi.add(post_hash);
    csi.add("\"");

    String csi_output = Command.runCommand(project_directory, csi);

 public static String runCommand(String directory, List<String> command) {


    ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File(directory));
    Process process;
    String output = null;
    try {
        process = processBuilder.start();

        //Pause the current thread until the process is done
        process.waitFor();

        //When the process does not exit properly
        if (process.exitValue() != 0) {

            //Error
            System.out.println("command exited in error: " + process.exitValue());

            //Handle the error
            return readOutput(process);
        }else {

            output = readOutput(process);
            System.out.println(output);
        }

    } catch (InterruptedException e) {
        System.out.println("Something wrong with command: " +e.getMessage());

    } catch (IOException e) {
        System.out.println("Something wrong with command: " +e.getMessage());
    }

    return output;
}

Ps:我确实想使用ProcessBuilder而不是Runtime.getRuntime.exec(),因为我需要在特定目录中运行该命令。我需要使用ProcessBuilder.directory()

Ps:运行后,命令将以2退出。系统似乎可以识别此命令。奇怪的是,退出2后它没有输出。

Ps:预期的命令是/bin/bash -l -c "/Users/ryouyasachi/GettyGradle/build/idea-sandbox/plugins/Getty/classes/python/csi 19f4281 a562db1"。我打印了这个值,这是正确的。

2 个答案:

答案 0 :(得分:0)

解决问题的最佳方法是首先构造命令并将其传递给列表。所以,而不是做这一切。

csi.add("/bin/bash");
csi.add("-l");
csi.add("-c");
csi.add("\"");
csi.add(csi_path);
csi.add(pre_hash);
csi.add(post_hash);
csi.add("\"");

您应该首先构建命令

StringBuilder sb = new StringBuilder();
sb.append("/bin/bash -l -c");
sb.append("\""+csi_path+pre_hash+post_hash+"\"");// add whitespace between the varaible, if required.
System.outprintln(sb.toString());  //verify your command here

csi.add(sb.toString());

另外,验证以上所有变量值。

答案 1 :(得分:0)

@Ravi的想法!

    //Construct the argument
    csi.add("/bin/bash");
    csi.add("-l");
    csi.add("-c");
    csi.add("\"" + csi_path + " " + pre_hash+ " " + post_hash + "\"");


    String csi_output = Command.runCommand(project_directory, csi);

Process必须分别取每个参数才能识别命令。棘手的部分是,在我理想的命令中 /bin/bash -l -c "/mypath/csi"

"/mypath/csi"需要被Process视为一个参数。