Java 不使用 Apache commons exec 执行 shellscript 中的所有命令

Java does not execute all commands in shellscript with Apache commons exec

我的行为很奇怪。

我有以下方法:

public static void loadMonitorsFromCron(){  
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    File ism_dir = new File("/var/app/ism/");
    String line = "/usr/bin/ksh /var/app/ism/ism_check_cron.ksh";
    CommandLine commandLine = CommandLine.parse(line);          
    try {
        DefaultExecutor exec = new DefaultExecutor();           
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);          
        exec.setWorkingDirectory(ism_dir);          
        exec.setStreamHandler(streamHandler);           
        exec.execute(commandLine);          
    } catch (ExecuteException e1) {
        System.out.println("ERROR: "+e1.getMessage());
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        System.out.println("ERROR: "+e1.getMessage());
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }       
    String[] paths = outputStream.toString().split("\n");

    System.out.println("Paths: ");
    for(int i=0;i<paths.length;i++)
        System.out.println(paths[i]);

    loadErrorCodeFromPath(paths);       
}

这是脚本:ism_check_cron.ksh 我正在尝试执行:

#!/usr/bin/ksh

echo "inbound_monitor.ksh"
echo "$(crontab -l | grep ism | grep -v '#' | cut -d ' ' -f 6 | cut -d '/' -f 5)"
echo "ism_heapdump.ksh"

当我查看 systemOut 的输出时,我只看到了这个:

SystemOut     O Paths:
SystemOut     O inbound_monitor.ksh
SystemOut     O
SystemOut     O ism_heapdump.ksh

crontab -l 本来应该列出许多其他字符串,如上面的字符串,但如您所见,我通过 Java.

什么也没得到

如果我在 Linux 终端中执行脚本,它工作正常。由于 Java 可以执行脚本的 'some part' 我也假设该方法也很好。所以我完全迷路了。有什么提示吗?

========更新=========

问题已解决,以后的读者可以参考下面的评论。

Java 是 运行 一个我没想到的用户。按照@Piotr R 的建议,我通过在 crontab -l 命令中添加 -u 参数解决了这个问题:

echo "$(crontab -u myuser -l | grep ism | grep -v '#' | cut -d ' ' -f 6 | cut -d '/' -f 5)"

在没有 -u 选项的情况下执行 crontab -l 将仅列出当前用户的 crontab 条目。

解决办法是用-u参数指向实际用户:

echo "$(crontab -u myuser -l | grep ism | grep -v '#' | cut -d ' ' -f 6 | cut -d '/' -f 5)"

第二种解决方案是为 运行 您的 java 程序的用户添加所有 crantab 条目,并从不需要它们的用户中删除条目。