Monday, June 18, 2012

Executing a Shell Script From a java Class

In this post I am going to explain the way of executing a shell script through a java class. But this kind of implementations are discourage by java programming language since this will remove the great power of java which is portability. (compile one one machine and can run on anywhere we have JRE). For this purpose we can use java ProcessBuilder and execute shell script file with the help of it.

private static void executeProcess(Operation command, String database) throws IOException,
            InterruptedException {

        final File executorDirectory = new File("src/main/resources/");

      
private final static String shellScript = "./sample.sh";
     
           ProcessBuilder processBuilder = new ProcessBuilder(shellScript, command.getOperation(), "argument-one");
      

        processBuilder.directory(executorDirectory);

        Process process = processBuilder.start();

        try {
            int shellExitStatus = process.waitFor();
            if (shellExitStatus != 0) {
                logger.info("Successfully executed the shell script");
            }
        } catch (InterruptedException ex) {
            logger.error("Shell Script preocess is interrupted");
        }

    }

In this case my shell script is reside in resources folder. You can see I have set the process builder directory to that, so the commands are executing from that directory.And also we can pass any number of arguments to shell script via process builder.In this case we have pass a single parameter to the shell script and from the shell script it can be accessed by $1. Following is the sample shell script we have invoked through the java class.
   echo "Sample script is executing"
   echo "parameter is :" $1 
Same way you can invoke a windows batch file as well.

7 comments:

  1. Hi Eshan,

    how do i call a .sh file from java program.

    reply me asap.

    Thanks&Regards,
    siva

    ReplyDelete
  2. Hi Siva,
    As you can see here I have executes a sh file. ("./sample.sh").
    For the bat file also you can use the same way. :)

    ReplyDelete
  3. Hi,
    I'm executing ProcessBuilder processBuilder = new ProcessBuilder("./Test.sh");
    Test.sh file is residing in the same directory from where i'm calling but its giving me below error.
    Exception in thread "main" java.io.IOException: CreateProcess: .\Test.sh error=193

    ReplyDelete
  4. HI Eshan

    how do i call the same ./Test.sh from mac terminal using java eclipse

    Regards,
    Harsh

    ReplyDelete
  5. HOw to exceute a shell script from remote unix machine using java?

    ReplyDelete
  6. i tried this.
    What is Operaction command?
    could you pls share the whole code

    ReplyDelete