How to run Unix shell script from Java code?
To run a Unix shell script from Java code, you can use the Runtime.getRuntime().exec() method to execute the script.
To run a Unix shell script from Java code, you can use the ProcessBuilder class, which is the modern standard for starting processes. It avoids parsing issues with spaces in paths and provides better control over the process.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
String scriptPath = "/path/to/script.sh";
ProcessBuilder processBuilder = new ProcessBuilder(scriptPath);
processBuilder.redirectErrorStream(true);
try {
Process process = processBuilder.start();
int exitCode = process.waitFor();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
if (exitCode == 0) {
System.out.println("Script executed successfully");
} else {
System.out.println("Script failed with exit value: " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}In this example, ProcessBuilder starts the script.sh script, and waitFor() blocks until the script finishes, returning the exit code directly. We also consume the standard output stream to prevent potential deadlocks if the script produces output. The try-catch block handles IOException and InterruptedException, which are thrown by process execution methods.
You may also need to set the executable flag on the script file using the chmod command before you can execute it from Java.