1

How can I run a shell script, written in Bash on Ubuntu, from Java in a Windows 10 environment?
I'm trying to use this code but it is not running nor executing the script.

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        ProcessBuilder builder = new ProcessBuilder(
            "bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");

        Process p = builder.start();
        BufferedReader r = new BufferedReader(new 
        InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line != null) {  System.out.print(line);}
            else{break;}   
        }
    }
VPK
  • 3,010
  • 1
  • 28
  • 35

2 Answers2

0

First of all: did you try to execute this command from command line? If you did and it worked it means that problem is not with bash on windows but with your java program.

If you cannot execute it from command line then fix this problem first

I cannot test my program because I use Ubuntu but can advice you to try smth like this: (wait until program is over)

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder(
                "bash.exe", "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh");

        Process p = builder.start();

        /* waitFor() method stops current thread until this process is over */
        p.waitFor();
        // I think that scanner is a nicer way of parsing output
        Scanner scanner = new Scanner(p.getInputStream());
        while (scanner.hasNextLine()) {
            // you do not have to create `line` outside the loop
            // it does not change performance of a program
            String line = scanner.nextLine();
            System.out.println(line);
        }
    }
}
0

If you are trying to run a script using Java in a Windows environment, I would suggested executing it differently.

I have adapted you code from a precious question asked here :

How to run Unix shell script from Java code?

Also, this question will help you with your question: Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)

public static void main(String[] args) throws IOException {

    Process proc = Runtime.getRuntime().exec(
            "/mnt/d/Kaldi-Java/kaldi-trunk/tester.sh"); 
    BufferedReader read = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

    while (read.ready()) 
    {
        System.out.println(read.readLine());
    }

}

I believe this is what you are looking for. I believe that your Java code was a little off and these edits should help you. After you build the java executable, you could be able to run it via Window's Command Prompt.

Mona Wade
  • 192
  • 1
  • 16