10

I am trying to execute a Bash Shell script from Java and it runs fine using this piece of code.

public void executeScript() {
    try {
        new ProcessBuilder("myscript.sh").start();
        System.out.println("Script executed successfully");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The above code runs fine asynchronously. But what I would like to achieve is to execute the code synchronously. I would like the Java process to wait until the execution of the script is completed and then execute the next batch of code.

To summarize, I would like the "Print statement - Script executed successfully" to be executed after the batch file ("myscript.sh") completes execution.

Thanks

Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
user1295300
  • 103
  • 1
  • 1
  • 7
  • take a look on this question http://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code – Tareq Salah Dec 15 '13 at 07:54
  • 1
    The link talks about using Runtime.getRuntime().exec. This is also asynchronous. I am looking for a "synchronous" solution. – user1295300 Dec 15 '13 at 08:14

3 Answers3

23

You want to wait for the Process to finish, that is waitFor() like this

public void executeScript() {
  try {
    ProcessBuilder pb = new ProcessBuilder(
      "myscript.sh");
    Process p = pb.start();     // Start the process.
    p.waitFor();                // Wait for the process to finish.
    System.out.println("Script executed successfully");
  } catch (Exception e) {
    e.printStackTrace();
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

The above code doesn't work if I wanted to move a file from one location to another, so I've fixed it with below code.

class Shell

{

  public static void main(String[] args) {
    try {
      ProcessBuilder pb = new ProcessBuilder("/home/sam/myscript.sh");
      Process p = pb.start();     // Start the process.
      p.waitFor();                // Wait for the process to finish.
      System.out.println("Script executed successfully");
    } catch (Exception e) {
      e.printStackTrace();
      }

  }
}


myscript.sh
#!/bin/bash   
mv -f /home/sam/Download/cv.pdf /home/sam/Desktop/
rgaut
  • 3,159
  • 5
  • 25
  • 29
2

Use Process#waitFor() to pause the Java code until the script terminates. As in

    try {
        Process p = new ProcessBuilder("myscript.sh").start();
        int rc = p.waitFor();
        System.out.printf("Script executed with exit code %d\n", rc);
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190