Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make java program return value to calling shell script

Tags:

java

shell

unix

Unix gurus!

I have a Java program which passes some parameters to a Servlet. The Servlet enters the info into a DB and returns back the ID of a row created back to the java program that calls it. The Java program is run in a Unix shell script, which later goes on to call another java program Java Program_2 (say).

My issue is this - I need to pass the ID we get from Java Program as a parameter to Java Program_2 in that same shell script. ARe there any best practice for this?

Things i am working with so far -

1) Make the java program return an exit code with System.exit(). 2 questions with this - How do i catch the exit code in a variable in the shell? Is this the right way to do it? Exit code is actually meant for returning the success parameter of the program...

2) Write the output in a file java Java_Program >opt.txt. If I do this, then how do I read the contents of opt.txt in a shell variable again?

Thanks a lot!

Edit: I should have mentioned this before actually... the programs are in different machines. I ssh into the other machine using the script..and then run java program 2. Hence, I cannot pipe the two.

like image 733
Jai Avatar asked May 20 '11 13:05

Jai


3 Answers

I would not recommend using the exit status to carry data, for the reasons you've stated. Catching the exit status depends on what shell you're using, but in Bash, the special $? variable contains the exit status of the last process executed.

Writing data to stdout is far more idiomatic. In Bash, you capture it as follows:

output=$(java Java_Program)

or:

output=`java Java_Program`

(You will often hear arguments that the first syntax is to be preferred.)

You can then feed this to stdin of your next process with:

echo $output > java Java_Program_2

More simply, you can simply pipe your processes together:

java Java_Program | java Java_Program_2
like image 74
Oliver Charlesworth Avatar answered Oct 15 '22 15:10

Oliver Charlesworth


I'm not sure if I missed something but it sounds to me that you could just let the first program write to stdout and pipe both programs together, couldn't you? You wouldn't even need a shellscript.

like image 29
b.buchhold Avatar answered Oct 15 '22 13:10

b.buchhold


In your Java Program print out the id using System.out.println(id);

In your shell script you can execute the Java Program and store the id in a variable. For example:

ID=$(java JavaProgram)

Now, execute Java Program_2 with the id:

java JavaProgram2 $ID

In Java Program_2, the ID will come into your main method in args[0].

You can even do this in a single step:

java JavaProgram2 $(java JavaProgram)

By the way, if you have output in a file called opt.txt you can read its contents into a variable like this:

CONTENTS=$(cat opt.txt)
like image 38
dogbane Avatar answered Oct 15 '22 13:10

dogbane