【发布时间】:2018-04-22 08:22:47
【问题描述】:
我正在尝试使用进程构建器在 java 中获取 grep linux shell 命令的输出。但我在这种情况下陷入困境。请帮我。 多谢指教!
String[] args = new String[7];
args[0] = "/bin/bash";
args[1] = "-c";
args[2] = "grep";
args[3] = "-n";
args[4] = "-e";
args[5] = "KERNELVERSION";
args[6] = kernelFilePath.trim();
ProcessBuilder pb;
Process process = null;
try {
pb = new ProcessBuilder(args);
pb = pb.directory(new File(directory));
pb.inheritIO();
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
process = pb.start();
process.waitFor();
} catch (IOException | InterruptedException e) {
System.out.println("executeCmdWithOutput() exception : " + e.toString());
} finally {
if (process != null) {
process.destroy();
}
}
==> 错误:
用法:grep [OPTION]... PATTERN [FILE]...
尝试“grep --help”以获取更多信息。
我在 bash 中尝试了该命令,它运行良好:
grep -n -e KERNELVERSION ..../Makefile
【问题讨论】:
-
完整命令必须作为单个参数传递给 bash:
args[2] = "grep -n -e KERNELVERSION " + kernelFilePath.trim();