javashellkshapache-commons-exec

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


I'm getting such an strange behavior here.

I have the following method:

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);       
}

And this is the script: ism_check_cron.ksh I am trying to execute:

#!/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"

When I look the output from systemOut, I just see this:

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

The crontab -l were supossed to list many other strings like the above ones, but as you can see, I got nothing through Java.

If I execute the script in the Linux terminal it works fine. As the Java can execute 'some part' of the script I also assume that the method is also fine. So I am completely lost. Any hint?

======== UPDATE =========

Problem solved, future readers can refer to the comments below.


Solution

  • Executing crontab -l without the -u option will list only the current user crontab entries.

    The solution is to point the actual user with the -u parameter:

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

    Second solution is to add all crantab entries for user that is running your java program and remove entries from the user that doesn't need them.