简体   繁体   中英

how to integrate Bash with Java

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.

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
}  

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());

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM