记录的输出显示了运行的命令,可以看出这包括一个 bash
命令:
thufir@dur:~/NetBeansProjects/threadedExecTelnet$
thufir@dur:~/NetBeansProjects/threadedExecTelnet$ gradle run
> Task :run
May 19, 2020 12:25:47 P.M. net.bounceme.dur.exec.ExecList execute
INFO: [bash, -c, ls /home/thufir/NetBeansProjects/threadedExecTelnet]
build
build.gradle
gradle
gradlew
gradlew.bat
LICENSE
README.md
settings.gradle
src
BUILD SUCCESSFUL in 859ms
3 actionable tasks: 1 executed, 2 up-to-date
thufir@dur:~/NetBeansProjects/threadedExecTelnet$
虽然我不太介意费力且冗长的代码:
public void execute() throws IOException {
log.info(listToExec.toString());
String[] arrayToExec = listToExec.toArray(new String[0]);
Process process = Runtime.getRuntime().exec(arrayToExec);
InputStream inputStream = process.getInputStream();
Reader inputStreamReader = new InputStreamReader(inputStream);
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
System.out.flush();
}
}
}
我不明白为什么有时似乎需要 bash
,有时则不需要。
最佳答案
对于内置于 shell 中的命令,第一个参数必须是 shell。但是,如果要运行的命令是普通的可执行文件,那么直接使用限定路径应该可以工作。对于“ls”,您可以检查:
which ls
这可能会打印/bin/ls 或类似的内容,因此您可以尝试从 Java 启动而不使用 bash:
listToExec = new String[] {"/bin/ls", "/home/thufir/NetBeansProjects/threadedExecTelnet"}
请注意,有些人可能有“ls”的 shell 别名,因此在正常的 bash session 中或通过 java 调用“bash -c ls blah”直接使用/bin/ls 与“ls”可能会有不同的行为
关于java - 从 Java 运行 exec 命令是否需要 "bash"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61899341/