简体   繁体   English

如何在 shell 脚本中检查 JAVA 程序是否成功执行?

[英]How to check if the JAVA Program successfully executed in shell scripting?

I am running java program from shell script.我正在从 shell 脚本运行 java 程序。 I need to execute next step in same shell script based on if any exception occur in java program or it ran successful.I am aware that java doesn't run anything.我需要根据 java 程序中是否发生任何异常或运行成功,在同一个 shell 脚本中执行下一步。我知道 java 没有运行任何东西。 How can we do it in shell script?我们如何在 shell 脚本中做到这一点? I know that we can print some string in log and grep it to check the status.我知道我们可以在日志中打印一些字符串并打印 grep 来检查状态。 is there any better way to do this?有没有更好的方法来做到这一点? It would be good even if I can get some elegant way to do it using grep.即使我可以使用 grep 获得一些优雅的方法,它也会很好。

If a Java program was terminated because of an exception, the JVM will exit with an error status 1 , instead of the usual success status 0 .如果 Java 程序由于异常而终止,则 JVM 将以错误状态1退出,而不是通常的成功状态0 For example, this program exits because of a NullPointerException:例如,这个程序因为 NullPointerException 而退出:

shell$ cat Throw.java
public class Throw {
    public static void main(String[] args) {
        String s = null;
        System.out.println(s.length());
    }
}
shell$ java Throw 2>/dev/null; echo $?
1

You can use the exit status in a shell if-statement for example.例如,您可以在 shell if 语句中使用退出状态。 This will print boo :这将打印boo

if java Throw 2>/dev/null ; then
   echo woo
else
   echo boo
fi

If you want to set an exit code other than 1, use the System.exit(int status) function.如果要设置 1 以外的退出代码,请使用System.exit(int status) function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM