Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to build Executable jar to return string to shell script

I have to run executable jar file from shell script to get a string value. The executable jar can't return a value as the main returns void. I can't use System.exit(int) as jar has to return value of String type.

Please suggest.

like image 307
Bharath Reddy Avatar asked Sep 11 '26 23:09

Bharath Reddy


1 Answers

This data should be written to stdout (System.out in Java), and captured with $(command expansion).

Here's what all good Unix citizens (and far too few Java programs) make sure to do:

  • Write program result to stdout (System.out)
  • Write error messages and debugging to stderr (System.err)
  • Use System.exit(0) to indicate success (this is also the default if no System.exit is used)
  • Use System.exit(1) (or higher, up to 255) to indicate failure

Here's a complete example for demonstrating the interplay between Java and shell scripts:

$ cat Foo.java
class Foo {
  public static void main(String[] args) {
    System.out.println("This data should be captured");
    System.err.println("This is other unrelated data.");
    System.exit(0);
  }
}

A very basic manifest:

$ cat manifest
Main-Class: Foo

A simple shell script:

#!/bin/sh
if var=$(java -jar foo.jar)
then
  echo "The program exited with success."
  echo "Here's what it said: $var"
else
  echo "The program failed with System.exit($?)"
  echo "Look at the errors above. The failing output was: $var"
fi

Now let's compile and build the jar and make the script executable:

$ javac Foo.java
$ jar cfm foo.jar manifest Foo.class
$ chmod +x myscript

And now to run it:

$ ./myscript
This is other unrelated data.
The program exited with success.
Here's what it said: This data should be captured
like image 116
that other guy Avatar answered Sep 14 '26 13:09

that other guy