Tuesday, 20 March 2018

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();
        }
    }
}

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

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 multi-threading - Java Program
  4. Compressing And Decompressing File in GZIP Format - Java Program
  5. Print Odd-Even Numbers Using Threads And wait-notify - Java Program

You may also like -

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

6 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