Run shell script from Java Synchronously
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/
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();
}
}
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);