使用java运行shell脚本时出现问题

时间:2009-03-04 09:44:14

标签: java linux shell

我在test.sh文件夹中有一个名为/tmp/padm的shell脚本。 在那个shell脚本中,我有一个语句

echo "good"

我正在尝试使用Java代码运行shell脚本。

String cmd=("/tmp/padm/.test.sh");            
Runtime rt = Runtime.getRuntime();
Process pr=rt.exec(cmd);

但我的问题是我无法看到“好”这是shell脚本的输出。

如何让脚本运行?

6 个答案:

答案 0 :(得分:4)

您可以使用以下代码获取命令输出。希望这会有所帮助。

Process process = Runtime.getRuntime().exec(cmd);
String s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(process
            .getInputStream()));
while ((s = br.readLine()) != null)
{
   s += s + "\n";
}    
System.out.println(s);

BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while (br2.ready() && (s = br2.readLine()) != null)
{
  errOutput += s;
}
System.out.println(errOutput);

答案 1 :(得分:1)

那不行。您必须在脚本的第一行添加“hash bang”,告诉Linux它必须使用合适的解释器(例如bash)来解释脚本,或者通过Java显式地通过bash运行它。

答案 2 :(得分:1)

当你说“在终端上”是什么意思?如果您想查看您需要使用的流程的输出/错误:

process.getErrorStream();
process.getOutputStream();

除此之外,我可以从使用Runtime.exec调用shell脚本看到没有问题

答案 3 :(得分:1)

process.getErrorStream();
process.getOutputStream();

oxbow_lakes 指出的正确方法。

另外,请确保以shell脚本位置作为参数执行/bin/sh

答案 4 :(得分:1)

试试这个,肯定会有用。

Shell脚本test.sh代码

   #!/bin/sh
   echo "good"

Java代码执行shell脚本test.sh

          try {
                Runtime rt = Runtime.getRuntime();
                Process pr = rt.exec(new String[]{"/bin/sh", "/tmp/padm/.test.sh"});

                BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                String line = "";
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                System.out.println(e.toString());
                e.printStackTrace();
            }

答案 5 :(得分:0)

这是Need sample java code to run a shellscript的副本。

我的答案中的示例程序确实打印出标准错误和标准输出(示例程序稍后添加)。

请注意,streamGobblers在不同的线程中运行,以防止由于完整的输入/输出缓冲区而导致执行问题。

如果您希望当然可以让StreamGobblers将输出存储在列表中,并在执行该过程后检索列表,而不是直接将其转储到stdout上。

相关问题