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.
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.
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:
System.exit(0)
to indicate success (this is also the default if no System.exit is used)System.exit(1)
(or higher, up to 255) to indicate failureHere'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
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
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?
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