如果抛出未经检查的 Java 异常,则停止 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/587099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop bash script if unchecked Java Exception is thrown
提问by Tom Hawtin - tackline
I am running a java program from within a Bash script. If the java program throws an unchecked exception, I want to stop the bash script rather than the script continuing execution of the next command.
我正在从 Bash 脚本中运行 Java 程序。如果java程序抛出未经检查的异常,我想停止bash脚本而不是脚本继续执行下一个命令。
How to do this? My script looks something like the following:
这该怎么做?我的脚本如下所示:
#!/bin/bash
javac *.java
java -ea HelloWorld > HelloWorld.txt
mv HelloWorld.txt ./HelloWorldDir
回答by
In agreement with Tom Hawtin,
与汤姆·霍廷达成一致,
To check the exit code of the Java program, within the Bash script:
要检查 Java 程序的退出代码,请在 Bash 脚本中:
#!/bin/bash
javac *.java
java -ea HelloWorld > HelloWorld.txt
exitValue=$?
if [ $exitValue != 0 ]
then
exit $exitValue
fi
mv HelloWorld.txt ./HelloWorldDir
回答by Tom Hawtin - tackline
Catch the exception and then call System.exit. Check the return code in the shell script.
捕获异常,然后调用 System.exit。检查 shell 脚本中的返回码。
回答by Douglas Leeder
#!/bin/bash
function failure()
{
echo "$@" >&2
exit 1
}
javac *.java || failure "Failed to compile"
java -ea HelloWorld > HelloWorld.txt || failure "Failed to run"
mv HelloWorld.txt ./HelloWorldDir || failure "Failed to move"
Also you have to ensure that javaexits with a non-zero exit code, but that's quite likely for a uncaught exception.
此外,您必须确保java以非零退出代码退出,但这很可能是未捕获的异常。
Basically exit the shell script if the command fails.
如果命令失败,基本上退出 shell 脚本。

