2

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.

Bharath Reddy
  • 301
  • 2
  • 4
  • 15

4 Answers4

6

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
that other guy
  • 116,971
  • 11
  • 170
  • 194
0

Can you run a Java application that will launch a shell and capture the string from that? I am thinking of many applications which capture username / password from a shell. For example if using spring check out: https://github.com/spring-projects/spring-shell

GavinF
  • 387
  • 2
  • 15
  • The application needs to return the value to shell script. So from shell script I have to run the jar and catch the returned string value. – Bharath Reddy Jan 10 '17 at 23:38
0

Suggestion: Try to write your String to System.stdout and read it from there. Maybe you can write output to a file and read it from there?

upf
  • 96
  • 7
0

Another suggestion : Get the java application to save its output to a temporary file and then get the shell script to read in the contents of the file such as VAR=cat /tmp/temp_file

R. Salame
  • 21
  • 4