Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Java system exit value to bash script

Tags:

java

shell

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

like image 705
mike628 Avatar asked Sep 12 '13 12:09

mike628


2 Answers

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 $?
like image 56
P.P Avatar answered Oct 08 '22 11:10

P.P


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
like image 13
Danilo Muñoz Avatar answered Oct 08 '22 13:10

Danilo Muñoz