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 {
       process.wait();
       } catch (InterruptedException e) {
             e.printStackTrace();
       }
       BufferedReader pReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
       String data = null;
       while((data=pReader.readLine())!=null){
            builder.append(line);
       }
       String result = builder.toString();
       System.out.print(result);
  • Using Process Builder
    • Java Code to execute shell script using ProcessBuilder
 String cmd = "/home/javasavvy/sample_script.sh";  
//String cmd = "D://script.bat" //for windows
 ProcessBuilder pb = new ProcessBuilder(cmd); 
 try
 {
 Process process = pb.start();
 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
 StringBuilder builder = new StringBuilder();
 String line = null;
 while ( (line = reader.readLine()) != null) {
 builder.append(line);
 }
 String result = builder.toString();
 System.out.print(result);
 System.out.println("end of script execution");
 }
 catch (IOException e)
 { System.out.print("error");
 e.printStackTrace();
 }

 

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/sam_script.sh  admin passwod 127.0.0.1

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/sam_script.sh  admin passwod 127.0.0.1" ;
ProcessBuilder pb = new ProcessBuilder(cmd.split(" ")); 
Process pr = pb.start();

 

 

Hope this helps.

2 Comments

  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.

    Reply
  2. janish

    Very useful. Saved lot of time. Thank you

    Reply

Leave a Comment

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