【问题标题】:ProcessBuilder not executing command with wildcard [duplicate]ProcessBuilder不使用通配符执行命令[重复]
【发布时间】:2017-08-01 09:52:38
【问题描述】:

我正在尝试编写一个实用程序 java 程序,它在 unix 框中调用 perl 脚本并显示脚本的输出。问题是当我执行command2时,

String[] command2 = {"/archive/scripts/grep.pl", "/apps/ws/logs/api.log"};

输出正确。但是当我使用command1时,

String[] command1 = {"/archive/scripts/grep.pl", "/apps/ws/logs/*"};

我得到以下异常:

Can't open /apps/ws/logs/*: No such file or directory at /archive/scripts/grep.pl line 160.

以下是完整代码供您参考:

    StringBuffer output = new StringBuffer();
    try {
        ProcessBuilder processBuilder = new ProcessBuilder(command1);
        LOGGER.debug("Command: "+processBuilder.command());
        Process process = processBuilder.start();
        process.waitFor();
        BufferedReader br;
        if (process.exitValue() == 0) {
            LOGGER.debug("Inside if block. Exit value: "+process.exitValue());
            String line;
            br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = br.readLine()) != null) {
                output.append(line + "\n");
            }
        } else {
            LOGGER.debug("Inside Else block. Exit value: "+process.exitValue());
            br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                output.append(line + "\n");
            }
        }
    } catch (Exception e) {
        LOGGER.debug("Exception thrown"+e.getStackTrace());
        output.append(e.getStackTrace().toString());
        e.printStackTrace();
    }
    return output.toString();

我无法理解问题所在。有没有办法做到这一点。

【问题讨论】:

  • 该目录下是否有名称为* 的文件?文件掩码由 shell 解析。如果直接执行脚本,shell就被忽略了...
  • 没有名为 * 的文件。当我在框中运行命令/archive/scripts/grep.pl /apps/ws/logs/* 时,我得到了正确的输出。

标签: java unix wildcard processbuilder


【解决方案1】:

使用命令行解释通配符

String[] command1 = {"bash", "-c", "/archive/scripts/grep.pl /apps/ws/logs/*"};

【讨论】:

  • @Reimus 感谢您的建议。我尝试了您建议的代码。但是,我没有得到预期的输出。尽管错误不再出现。还注意到 exitValue 以255 的形式出现。
  • 检查来自ProcessBuilder 的错误流。在命令行上运行命令会发生什么?
  • 我得到以下输出:Scanning...Overall found 0 entries
  • 在错误流中我收到这条消息Usage: ./grep.pl [files to scan] e.g. ./grep.pl /apps/ws/logs/*,它是脚本内的注释,如die "Usage: ./grep.pl [files to scan]\ne.g. ./grep.pl /apps/tkt-ws/logs/*" unless defined @ARGV;
  • 命令需要被shell作为一个整体来解释,如更新所示...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 2011-04-16
  • 2014-03-14
  • 2016-08-08
  • 1970-01-01
  • 2017-03-07
  • 2017-05-27
相关资源
最近更新 更多