Java ProcessBuilder + bash:“没有这样的文件或目录”

时间:2019-07-06 12:27:40

标签: java windows bash

我正在尝试在Windows上从Java运行bash(在此使用Windows Linux子系统,但是Git Bash是相同的),但是即使基本操作也失败了:

bash --noprofile --norc -c 'echo $PWD'`

cmd.exe中可以正常工作:

Works fine in CMD.exe

在Java中:

import static java.util.stream.Collectors.joining;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;

public class ProcessBuilderTest {
    public static int runBatch() {
        List<String> commandLine = new ArrayList<>();
        // both following lines have the same result
        commandLine.add("bash");
        // commandLine.add("C:\\Windows\\System32\\bash.exe"); 

        commandLine.add("--noprofile");
        commandLine.add("--norc");
        commandLine.add("-c");
        commandLine.add("'echo $PWD'");

        System.out.println("cmd: " + commandLine.stream().collect(joining(" ")));
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
            Process process = processBuilder
                .redirectErrorStream(true)
                .start();
            new BufferedReader(new InputStreamReader(process.getInputStream())).lines()
                .forEach(System.out::println);
            return process.waitFor();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (InterruptedException e) { // NOSONAR
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        runBatch();
    }
}

运行上述结果将导致以下结果,并且该过程永不退出。

cmd: bash --noprofile --norc -c 'echo $PWD'
/bin/bash: echo /mnt/c/scratch/pbtest: No such file or directory

预期的行为:没有错误,过程终止。

2 个答案:

答案 0 :(得分:1)

bash在Windows环境中的cmd.exe中运行

您可以让Java运行以下命令吗?

cmd.exe /c bash --noprofile --norc -c 'echo $PWD'

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", 
    "/c", 
    "bash --noprofile --norc -c 'echo $PWD'");

或您最初尝试使用的列表

受到mkyong post

的启发

答案 1 :(得分:1)

使用Git-bash: 我更改了这两行,红外线按预期运行:

// Used full path to the underlying bash.exe shell
commandLine.add("\"C:\\Program Files\\Git\\bin\\bash.exe\"");

// Removed quotes
commandLine.add("echo $PWD"); 

参考:https://superuser.com/a/1321240/795145