簡體   English   中英

java - 通過Java DefaultExecutor和CommandLine執行shell腳本時如何檢索可能的shell腳本退出代碼?

[英]How to retrieve possible shell script exit codes when Executed shell script by Java DefaultExecutor & CommandLine?

我正在使用 Java 程序中的 DefaultExecutor 和 CommandLine 執行 shell 腳本。

成功執行接收 0 退出值

但是如果出現失敗或來自 shell 腳本的任何其他退出代碼(如 127,128,255 等) ,則不會收到相應的退出代碼,而是獲取 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);
}

任何想法如何處理退出代碼以執行特定的自定義操作?

DefaultExecutor::execute()文檔說它拋出

ExecuteException - 子進程的執行失敗或子進程返回了指示失敗的退出值

ExecuteExceptionIOException的子類,因此它會被您的代碼捕獲。 如果您嘗試(也)捕獲正確的異常,則可以使用其getExitValue()方法來獲取退出狀態。

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 succeeded with exit code " + iExitValue); // Always successful (0)
} catch (ExecuteException e) {
    log.info("Script failed with exit code " + e.getExitValue());
} catch (IOException e) {
    log.error("IOException occurred: ", e);
}

在探索更多之后,我能夠找出正確的答案。

對於成功退出代碼,將setExitValues()與成功代碼的 int 數組一起使用,而不是使用單個退出代碼作為整數值的“setExitValue()”

int[] codes = {0,127,128};
oDefaultExecutor.setExitValues(codes);

其余的失敗退出代碼將在 ExecuteException 塊中捕獲

catch (ExecuteException exe) {
    iExitValue = exe.getExitValue();
    log.info("Script failed with exit code: " + iExitValue);
}

完整的代碼片段和解決方案

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM