在java中调用shell脚本的问题

时间:2013-05-20 14:03:32

标签: java shell

我在java中调用一个shell脚本,它接收2个pameteres。

private void invokeShellScript(String script,String subject,String message)
    {
        String shellCmd = null;
        try
        {
            shellCmd = script.trim() + " " + subject + " " + message;

            Process process=Runtime.getRuntime().exec(shellCmd);
            process.waitFor();
        }
        catch(Exception e)
        {
             LOGGER.error("Exception occured while invoking the message report script");
        }
    }

这里,当我将主题和消息传递给shell脚本时,它没有正确解析内容。

这里说如果主题=“你好这是一个测试邮件”。 然后shell脚本需要 Hello ,并且消息为这个

这里我猜测字符串中的空格会导致问题。

我该如何解决这个问题。

3 个答案:

答案 0 :(得分:2)

在将字符串传递给shell时尝试引用字符串。

所以要么

"\"Hello This is a test mail\""

"'Hello This is a test mail'"

(在java中)

答案 1 :(得分:1)

您需要使用Runtime.exec版本,该版本需要String[]作为命令,而不是String,因此您可以控制将其拆分为单词的方式。或者更好的是,使用ProcessBuilder。您还需要在调用waitFor之前读取或显式丢弃进程的输出流,否则可能会阻塞

try {
  ProcessBuilder pb = new ProcessBuilder(script, subject, message);
  pb.redirectErrorStream(true);
  pb.redirectOutput(new File("/dev/null"));
  Process process = pb.start();
  process.waitFor();
}
catch(Exception e) {
  LOGGER.error("Exception occured while invoking the message report script");
}

Process.redirectOutput是Java 7的发明,如果您仍在使用6,则必须在调用process.getOutputStream()之前自己阅读并丢弃waitFor的内容。

答案 2 :(得分:0)

使用arraylist单独尝试将所有参数puttin并将其作为命令提供给ProcessBuilder

final List<String> commands = new ArrayList<String>();                

commands.add(Script.trim());
commands.add(subject);
commands.add(message);

ProcessBuilder pb = new ProcessBuilder(commands);

这应该可以正常工作,因为java会将它们视为单独的争论。