I am executing shell script using DefaultExecutor & CommandLine from Java Program.
For successful execution receiving 0 exit value
but in case of failure or any other exit code (like 127,128,255 etc.) from shell script, not receiving respective exit code instead getting IOException.
int iExitValue = 1;
CommandLine cmd = CommandLine.parse("sh /Users/DpakG/scripts/do_Database_Operations.sh");
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(cmd);
log.info("Script Exit Code: " + iExitValue);
} catch (IOException e) {
log.error("IOException occurred: ", e);
}
Any Idea How to handle exit code to perform specific custom action?
After exploring more, I am able to figure out right answer.
For Success exit codes, use setExitValues() with int array of success codes instead of 'setExitValue()' with single exit code as integer value.
int[] codes = {0,127,128};
oDefaultExecutor.setExitValues(codes);
Rest of the Failure exit codes would be captured within ExecuteException block
catch (ExecuteException exe) {
iExitValue = exe.getExitValue();
log.info("Script failed with exit code: " + iExitValue);
}
Complete code snippet with solution
int iExitValue = 1;
CommandLine cmd = CommandLine.parse("sh /Users/DpakG/scripts/do_Database_Operations.sh");
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
int[] successCodes = {0,127,128};
oDefaultExecutor.setExitValues(successCodes);
try {
iExitValue = oDefaultExecutor.execute(cmd);
log.info("Script succeeded with exit code " + iExitValue); // Either 0, 127 or 128
} catch (ExecuteException exe) {
iExitValue = exe.getExitValue();
log.info("Script failed with exit code: " + iExitValue);
} catch (IOException ie) {
log.error("IOException occurred: ", ie);
}