Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return some value to shell from Java program?

Tags:

java

linux

shell

I want to run a Java program from a shell script.So I did something like below

My test Java file is as follows

public class EchoTest {
    public static void main (String args[]) {
    System.out.println ("scuccess ..!!");
}

My test shell script file is as follows

out=$(java EchoTest)    
echo $out

I have compiled the java program, and then I did run that shell script (like $sh Myscript.sh). Now it printed the output onto console.Upto now it is working fine.

If I write a program like below (which throws some exception)

  public class EchoTest {
        public static void main (String args[]) {
        System.out.println ("Value is "+(2/0));
    }

it is just printing the java exception onto console. But my requirement is that I want it to print 0 or 1 onto console, i.e I want to get 0(zero) when my java program fails and want to get 1(one) when java program executes successfully .

like image 877
prasad Avatar asked Jul 28 '15 15:07

prasad


2 Answers

The documentation from the java program says :

EXIT STATUS

The following exit values are generally returned by the launcher, typically when the launcher is called with the wrong arguments, serious errors, or exceptions thrown from the Java Virtual Machine. However, a Java application may choose to return any value using the API call System.exit(exitValue).

  • 0: Successful completion.
  • >0: An error occurred.

So if you do not do anything, the JVM follows the common convention of returning a 0 value to the caller on successfull completion and a non null value in case of error.

Your shell script should then be :

java EchoTest
if [ $? -eq 0]
then echo 1
else echo 0
fi

That means that you can ignore standard output and standard error and just rely on the exit status from the JVM.

As suggested by @alk, you can even replace first line with out = $( java EchoTest ) and use $out in the success branch (when $? is 0)

like image 51
Serge Ballesta Avatar answered Sep 27 '22 20:09

Serge Ballesta


you need to use System.exit(code) with the code you want depending if you detect an error/exception or not

you will have

System.exit(0) // if you detect error, you need to handle exception
System.exit(1) // when no error
like image 40
Frederic Henri Avatar answered Sep 27 '22 21:09

Frederic Henri