【发布时间】:2016-08-04 14:02:40
【问题描述】:
我正在编写一个 Java 程序,从中执行一个 shell 脚本。 shell 脚本正在调用另一个 shell 脚本。我正在尝试将子脚本返回的输出打印到父 shell 脚本。 下面是我的代码。
public class App
{
public static void main( String[] args ) throws IOException, InterruptedException
{
String command = new String("/home/Test.sh");
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(command);
process.waitFor(1, TimeUnit.MINUTES);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}
Shell 脚本:Test.sh
#!/bin/bash
result=$( bash myscript.sh )
echo "$result"
myscript.sh
#!/bin/bash
echo "50"
我得到空输出。我最初认为这可能是因为 Java 进程没有等待 shell 脚本完成。所以添加了 waitFor() 但仍然没有用。有人可以帮忙吗?
【问题讨论】:
-
检查错误流,因为它适用于我的代码
-
试试这个; result=$( bash /home/myscript.sh ) , myscript.sh 的完整路径