/**
* execute shell script
*/
private static void executeScript() {
try {
String bash = "/bin/bash";
String script = "script.sh";
String[] command = { bash, script };
System.out.println("Starting execute the script");
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> env = processBuilder.environment();
env.put("ENV_KEY", "ENV_VALUE");
Process process = processBuilder.start();
// output the process
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
// wait for the end of process
process.waitFor();
System.out.println("Script executed successfully");
} catch (Exception e) {
throw new RuntimeException("Can not execute the install script successfully");
}
}
ProcessBuilder is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.