java - Java ProcessBuilder + bash:“没有这样的文件或目录”
问题描述
我正在尝试在 Windows 上从 Java 运行 bash(这里使用的是 Windows Linux 子系统,但 Git Bash 是一样的),但即使是基础知识也失败了:
bash --noprofile --norc -c 'echo $PWD'`
在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
预期行为:没有错误并且进程终止。
解决方案
bash
cmd.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 帖子
推荐阅读
- c# - 带有 signalR 的属性的别名
- html - 如果 Bulma 工具提示在 y 上滚动的 xa 父容器上溢出,如何使其可见
- apache-kafka-streams - RocksDB 的 Kafka Streams 内存分配问题
- javascript - 将数据保存到 LocalStorage,然后使用 android Java 检索它
- java - 在 JpaRepository 中刷新 saveAll
- svg - Safari SVG 蒙版渲染故障(剪辑路径)
- c++ - 正在调用基类虚拟方法,而不是子类的覆盖实现
- forms - getEditResponseUrl -> 某些行的空白表格
- python - 在 python 中创建后台任务并与之交互
- java - 将 json 反序列化为可选列表不会获得数组元素