Saturday, March 20, 2021

How to Run a Shell Script From Java Program

This post talks about how you can execute a shell script from a Java program.

If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).

Shell script

echo 'starting script'
mkdir test
cd test
touch SAMPLE

Using Runtime.getRunTime().exec to execute shell script

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunningSS {
 public static void main(String[] args) {
  Process p;
  try {
   String[] cmd = { "sh", "/home/adb/Documents/test.sh"};
   p = Runtime.getRuntime().exec(cmd); 
   p.waitFor(); 
   BufferedReader reader=new BufferedReader(new InputStreamReader(
    p.getInputStream())); 
   String line; 
   while((line = reader.readLine()) != null) { 
    System.out.println(line);
   } 
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

After executing this Java program with the given shell script, if you verify at the location where your Java program is you will see a directory test created and a file SAMPLE with in that directory.

Runtime.getRuntime().exec method is used to run the command.

  • public static Runtime getRuntime() - Returns the runtime object associated with the current Java application.
  • public Process exec(String command) throws IOException - Executes the specified string command in a separate process.

cmd /c which is used with the command has the following explanantion -

  • cmd- Starts a new command shell
  • /c- Executes the given command and terminates

Execution of the command returns instance of class Process. Using the getInputStream() method of Process class output of the executed command can be printed by reading the stream.

Using ProcessBuilder to execute shell script in Java

If you have to run the same command as above using ProcessBuilder, which is a much clearer way to do that, you can create a list with the command and the required arguments and then pass it to ProcessBuilder instance as command.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class RunningSS {
  public static void main(String[] args) {
    Process p;
    try {        
      List<String> cmdList = new ArrayList<String>();
      // adding command and args to the list
      cmdList.add("sh");
      cmdList.add("/home/adb/Documents/test.sh");
      ProcessBuilder pb = new ProcessBuilder(cmdList);
      p = pb.start();
                
      p.waitFor(); 
      BufferedReader reader=new BufferedReader(new InputStreamReader(
       p.getInputStream())); 
      String line; 
      while((line = reader.readLine()) != null) { 
        System.out.println(line);
      } 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

That's all for this topic How to Run a Shell Script From Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Running Dos/Windows Commands From Java Program
  2. How to Compile Java Program at Runtime
  3. How to Create Deadlock in Java
  4. Compress And Decompress File Using GZIP Format in Java
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. Producer-Consumer Java Program Using volatile
  2. Java Program to Get All The Tables in a DB Schema
  3. Generating Getters And Setters Using Reflection in Java
  4. Encapsulation in Java
  5. Difference Between throw And throws in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. Difference Between CountDownLatch And CyclicBarrier in Java
  8. Java StampedLock With Examples

11 comments:

  1. when i tried running your program .
    List cmdList = new ArrayList();
    // adding command and args to the list
    cmdList.add("sh");
    cmdList.add("C:\\Users\\mahesh.x.kuma\\Documents\\test\\test.sh");
    ProcessBuilder pb = new ProcessBuilder(cmdList);
    p = pb.start();

    i am getting error
    java.io.IOException: Cannot run program "sh": CreateProcess error=2, The system cannot find the file specified

    ReplyDelete
    Replies
    1. You are trying to run shell script on a Windows system! What do you expect ???

      Delete
  2. I am getting below exception:
    java.io.IOException: Cannot run program "sh": CreateProcess error=2

    Help me out resolve the issue.
    Can you explain what is "sh"

    ReplyDelete
    Replies
    1. the extension of your file. Here you are executing test.sh, so you need to pass the extension so that system knows how to handle this file.

      Delete
  3. This is perfectly explained, thank you so much for posting this.

    ReplyDelete
  4. when i try to run this for rpi script is not executing, I need to run the script manually then only its running

    ReplyDelete
  5. I want to run multiple scripts from java code.How to do this?

    ReplyDelete
  6. java.io.IOException: Cannot run program "sh": CreateProcess error=2, The system cannot find the file specified -- while execute this program i'm getting above issue. Team, please can any one look into this and provide the solution.
    public static void main(String[] args) {
    Process p;
    try {
    String[] cmd = { "sh", "C://Users//E5601972//Documents//sample.sh"};

    p = Runtime.getRuntime().exec(cmd);
    p.waitFor();
    BufferedReader reader=new BufferedReader(new InputStreamReader(
    p.getInputStream()));
    String line;
    while((line = reader.readLine()) != null) {
    System.out.println(line);
    }
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    ReplyDelete
    Replies
    1. You are trying to run shell script on a Windows system! What do you expect ??? Though there are ways to run sh from widows but that will require some work. You can't just rum a sh file from windows command line.

      Delete
  7. If you are using Windows replace "sh" with "cmd". The terminal of is "powershell" or "cmd". "sh", "/bin/bash", "/usr/bin/python" for other kinds of scripts.

    ReplyDelete
  8. This method works fine when I try to execute on local. But when I run a jar file it gives File or directory not found exception.

    ReplyDelete