Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active February 8, 2019 16:57
Show Gist options
  • Save simonwoo/c21811eddf0392034946 to your computer and use it in GitHub Desktop.
Save simonwoo/c21811eddf0392034946 to your computer and use it in GitHub Desktop.
/**
* 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment