1

Can any body help me with how to compile a bash script as part of a java program. I am writing a simple java program that i want to use to invoke bash script commands.


my java code looks like the following:

    try{
            Process p = Runtime.getRuntime().exec("myscript.sh"); 
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 

        String line = null;  

        while ((line = in.readLine()) != null){  
                    System.out.println(line); 
        }  
    }
    catch(IOException e){
        System.out.println(e.getMessage());
    }

and the "mysrcipt.sh" file is a simple script that contains the following lines


!/bin/bash

echo "enter your input followed by [ENTER]:"

read -e choice

echo $choice


My problem is, the program waits for an input at the read command in the script even if i enter multiple lines and press enter several times.

Community
  • 1
  • 1
The Coder
  • 557
  • 1
  • 7
  • 10

3 Answers3

3

You can use:

Process p = Runtime.getRuntime().exec("bash_script.sh"); 
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
String line = null;  
while ((line = in.readLine()) != null) {  
   // use bash script line output
}  
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

It would be helpful to see some code showing what you're trying to accomplish.

Executing bash script in Java can be done using something like the following...

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("YOUR COMMAND STRING");

List<String> lines = IOUtils.readLines(process.getInputStream());
shortstuffsushi
  • 2,271
  • 19
  • 33
  • 1
    That's `org.apache.commons.io.IOUtils`, incidentally, not the standard Java libs. – DNA Sep 18 '12 at 22:15
  • Good point, I snatched that out of a piece of code I wrote a while ago and didn't check the imports. I +1'd Reimeus' answer for its more general form. – shortstuffsushi Sep 19 '12 at 00:47
1

Runtime.exec() is what you need to execute your bash script, but be aware there are a few pitfalls. I found this to be a good article when starting to call external scripts.

It is written for a windows platform, but a lot of what is discussed is relevant to *nix as well.

See also this question.

Community
  • 1
  • 1
TaninDirect
  • 458
  • 1
  • 7
  • 15