13

I am trying to get the return value from a java program ( System.exit(1);) into a shell script, but it seems like its returning the jvm exit code, which is always 0, if it doesnt crash. For testing purposes, this is the very first line in my main(). Anyone know how to do this?

My bash code:

java  bsc/cdisc/ImportData $p $e $t


#-----------------------------------------
# CATCH THE VALUE OF ${?} IN VARIABLE 'STATUS'
# STATUS="${?}"
# ---------------------------------------
STATUS="${?}"

# return to parent directory
cd ../scripts


echo "${STATUS}"

Thanks

1
  • 2
    Interesting, since that should just work. Any more details? Also, why the curly braces? Commented Sep 12, 2013 at 12:20

2 Answers 2

22

If your script has only the two lines then you are not checking for the correct exit code.

I am guessing you are doing something like:

$ java YourJavaBinary
$ ./script 

where script contains only:

STATUS="${?}"
echo "${STATUS}"

Here, the script is executed in a subshell. So when you execute the script, $? is the value of last command in that shell which is nothing in the subshell. Hence, it always returns 0.

What you probably wanted to do is to call the java binary in your script itself.

java YourJavaBinary
STATUS="${?}"
echo "${STATUS}"

Or simply check the exit code directly without using the script:

$ java YourJavaBinary ; echo $?
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, I am calling the java binary within my code, and no thats not all that's in the script. I just put up the error reporting part.
So you have java YourJavaBinary ; STATUS="${?}" ; echo "${STATUS}" in the script and still it doesn't give the correct exit code in your script? If that's case, then it's strange. May be, can you show the whole part relating to the call to java and exit code checking and Can you produce the same issue with a simple java program that does only System.exit(1); ?
Just to reiterate it, you don't have any statements (excluding comments) between java ... and STATUS="${?}" right? :) Can you reproduce the problem I described in my previous comment?
13

You should do like this:

Test.java:

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

test.sh

#!/bin/bash

java Test
STATUS=$?
echo $STATUS

2 Comments

Yes! You're right. I had the solution in my pocket and I used it, but I don't know why a understood wrong. Should I vote to delete my answer?
Danilo, Thats exactly what I have.( and had) . I didnt post the entire script, because most is irrelevent.

Your Answer

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