7

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"

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any other way to capture the status since in java System.exit() is not normal way to exit.
you can catch status using echo $?, even if java program does not exits with System.exit(), by default it returns 0 (means Success) status to Operating System on normal exit of program.
2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.