Running a shell script using process builder in java


Running shell script using process builder java: Linux shell scripts or windows bat scripts will called using Java with below approaches. Always use ProcessBuilder as recommended approach:

  • Using Runtime.exec() 
    • Java code to execute shell script :
    •  StringBuilder builder = new StringBuilder();
       Process process = Runtime.getRuntime().exec("ps -ef");
       try {
       } catch (InterruptedException e) {
       BufferedReader pReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
       String data = null;
       String result = builder.toString();
  • Using Process Builder
    • Java Code to execute shell script using ProcessBuilder
 String cmd = "/home/javasavvy/";  
//String cmd = "D://script.bat" //for windows
 ProcessBuilder pb = new ProcessBuilder(cmd); 
 Process process = pb.start();
 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
 StringBuilder builder = new StringBuilder();
 String line = null;
 while ( (line = reader.readLine()) != null) {
 String result = builder.toString();
 System.out.println("end of script execution");
 catch (IOException e)
 { System.out.print("error");


How to pass arguments to shellscript using java?

suppose you want to execute a shell script with attributes like admin,password,url like show in below :

    /home/jay/  admin passwod

you can pass whole shell commnad as String array like show below:

Java code to launch shell script with arguments using Java ProcessBuilder:

String cmd= " /home/jay/  admin passwod" ;
ProcessBuilder pb = new ProcessBuilder(cmd.split(" ")); 
Process pr = pb.start();



Hope this helps.

Leave a Comment

Your email address will not be published. Required fields are marked *