Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

bash - Run shell script from Java Synchronously

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...