For example we are executing the below statement and we want to process further based on the status of java execution.
java -classpath $CLASSPATH com.heb.endeca.batch.BatchManager "param1" "param2" "param3"
If your Java code exits with System.exit(status), you can get the status in Bash like this:
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 finished process.
As other's have stated, you need to use the System.exit() to get the desired output. The reason behind this is that System.exit() directly teminates the programs and exits returning the value as defined.
If you were wondering why we couldn't return anything from the main method, the answer is - in java main method never returns anything, if you analyze the golden required statement
public static void main()
you would see, in java main has a return type as void.
So, if you are checking for the return status of a java program from the calling program (Shell in this case), you are trying to read actually the exit status of jvm and not of your java program which would in normal condition be always zero (0) even tough if you program crashed due to any exception. You would get a non-zero exit status only if the jvm crashes due to unexpected reasons like OutOfMemory or something similarly critical.
Hope this helps in your understanding of catching exit status of the java program.