首页 > 解决方案 > Java ProcessBuilder + bash:“没有这样的文件或目录”

问题描述

我正在尝试在 Windows 上从 Java 运行 bash(这里使用的是 Windows Linux 子系统,但 Git Bash 是一样的),但即使是基础知识也失败了:

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

cmd.exe这工作正常:

在 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

预期行为:没有错误并且进程终止。

标签: javawindowsbash

解决方案


bashcmd.exe在您的 Windows 环境中运行

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

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

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

或使用您最初尝试的列表

灵感来自mkyong 帖子


推荐阅读