Return Java system exit value to bash script
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
Solution 1:
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 $?
Solution 2:
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