ProcessBuilder调用脚本执行
最近在搞一些topic,需要用到ProcessBuilder去执行shell脚本,结果一直失败,报错如下:
/bin/bash: wget: command not found
贴上原先代码:
ProcessBuilder pb = new ProcessBuilder("/bin/bash","-c",command);
pb.redirectErrorStream(true); // 合并错误流到标准输出流
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line =reader.readLine()) != null) {
sb.append(line);
}
int exitCode = process.waitFor();
以上代码执行后报错。
排查思路:
1./bin/bash有问题,终端执行命令:echo $SHELL
我的命令行输出如下:/bin/zsh,修改ProcessBuilder的入参改为”/bin/zsh“,继续执行,报错。
2.ProcessBuilder有问题?尝试debug,发现命令传入没问题,问题还是回到/bin/bash
3.wget已经安装了,再命令行执行脚本毫无问题,但是到ProcessBuilder就报错。最后解决办法如下:
在终端执行如下命令行: which wget https:xxx,执行后输出"/usr/local/bin/wget"
修改ProcessBuilder的入参为/usr/local/bin/wget
基础用法:Java ProcessBuilder|极客教程