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.


  1. Divakar

    This Helped me a lot. I searched many places to find out Java code to launch shell script with arguments using Java ProcessBuilder exactly mentioned above.
    i.e I have to copy a file inside a Unix server the user should give the existing Shell Script name and the Arguments for the SH file is Filename1(Source) and FileName2(Destination) from the FrontEnd UI. cmd.splt(” “) inside the ProcessBuilder worked fine.
    Thanks for this Blog.

  2. janish

    Very useful. Saved lot of time. Thank you


Leave a Comment

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