How to get java program termination status from unix shell shell?

For example, we execute the statement below, and we want to continue processing depending on the execution status of Java.

java -classpath $CLASSPATH com.heb.endeca.batch.BatchManager "param1" "param2" "param3" 
+7
source share
3 answers

If your Java code terminated with System.exit(status) , you can get the status in Bash as follows:

Java:

 public class E { public static void main(String[] args) { System.exit(42); } } 

Bash:

 $ java E $ echo $? 42 

$? is the exit status of the last completed process.

+9
source

The java program should end with Sytem.exit (status). This number is returned like any other command in the operating system.

+2
source

As others have pointed out, you need to use System.exit() to get the desired result. The reason for this is that System.exit() directly executes the program and prints the return value as defined.

If you are wondering why we were unable to return anything from the main method, the answer is the java main method never returns anything if you parse the gold-requested statement

 public static void main() 

you will see that in java main there is a return type like void .

So, if you check the return status of the java program from the calling program (in this case, Shell), you are trying to actually read the exit status of the jvm , and not your java program, which would be in the normal condition should always be zero (0) even tough if you program a crash due to some kind of exception. You will only get non-zero exit status if jvm crashes due to unforeseen reasons like OutOfMemory or something like that.

Hope this helps in understanding that you will exit the java exit state.

0
source

All Articles