Learner Learner - 3 months ago 10
Bash Question

Java with shell Script

I am writing a Java program from which I am executing a shell script. The shell script is calling another shell script. I am trying to print output returned by child script to parent shell script.
Below is my code.

public class App
{
public static void main( String[] args ) throws IOException, InterruptedException
{
String command = new String("/home/Test.sh");
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(command);
process.waitFor(1, TimeUnit.MINUTES);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s);
}


Shell Script: Test.sh

#!/bin/bash
result=$( bash myscript.sh )
echo "$result"


myscript.sh

#!/bin/bash
echo "50"


I am getting empty output. I initial thought it might be because the Java process is not waiting for the shell script to finish. So added waitFor() but still no use. Can some one kindly help.

Answer

try this; this is not waiting problem.

#!/bin/bash
  result=$( bash /home/myscript.sh ) # full path of myscript
  echo "$result"

Also handle bash error as below;

public static void main(String[] args) throws IOException {
        String command = new String("/tmp/1/Test.sh");   
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec(command);
        BufferedReader reader = new BufferedReader(new InputStreamReader(        
                process.getInputStream()));

        String s;                                                                
        while ((s = reader.readLine()) != null) {                                
            System.out.println("Script output: " + s);   
        }

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(process.getErrorStream()));

        System.out.println("Here is the standard error\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }

    }
Comments