Executing a shell script from java using runtime.exec()

Hi I am trying to create a script (test_script) and execute it -- all within one java program...
the code compiles and executes perfectly but nothing happens. This is probably because the script does not get changed to the '777' mode although i am trying to do that ... any suggestions ???
//code
import java.io.*;
import java.util.*;
public class ScriptBuilder
     public ScriptBuilder() {
     public void writeScript() throws java.io.IOException{
     FileWriter writer = new FileWriter(new File("test_script"));
          writer.write("#! /bin/sh\n");
          writer.write("cd prodiags\n");
          writer.write("tar cvf delTask.tar delTask\n");
          writer.write("rm -rf delTask\n");          
          writer.flush();
          writer.close();
Runtime rt= Runtime.getRuntime();
String[] cmd = new String[3];
cmd[0] = "ls";
cmd[1] = "chmod 777 test_script";
cmd[2] = "./test_script";
rt.exec(cmd);
     public static void main (String[] args)throws java.io.IOException
     ScriptBuilder sb = new ScriptBuilder();
     sb.writeScript();
}

I don't know exactly but the code written below is working fine try the same with your code .Even with your code instead running the code with
" ./<filename> ",if you execute it with "sh <filename>" command without changing the mode of the file it is executing properly.
import java.io.*;
import java.util.*;
public class ScriptBuilder
public ScriptBuilder()
public void writeScript() throws java.io.IOException
FileWriter writer = new FileWriter(new File("test_script"));
writer.write("#! /bin/sh\n");
writer.write("ll>/home/faiyaz/javaprac/checkll");
writer.flush();
writer.close();
Runtime rt= Runtime.getRuntime();
rt.exec("chmod 777 test_script");
rt.exec("./test_script");
} public static void main (String[] args)throws java.io.IOException
ScriptBuilder sb = new ScriptBuilder();
sb.writeScript();
}

Similar Messages

  • How to execute unix shell script from Java ...

    Hi,
    Anyone know how to execute unix shell script from Java?
    Suppose I have several shell scripts written in perl or tcl or bash.
    I just want to catch the output of that script.
    Is there any ready to use module/object for this?
    Please let me know, this is quite urgent for my study assigment.
    Thanks in advance,
    Regards,
    me

    Look up Runtime.exec()

  • Error while executing unix shell script from java program

    Hi All,
    I am trying to execute unix shell script from a java program using Runtime.execute() method by passing script name and additional arguments.
    Code snippet :
    Java Class :
    try{
         String fileName ="test.ksh";
         String argValue ="satish"; // value passed to the script
         String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
         Process proc = Runtime.getRuntime().exec(exeParam);
         int exitValue = proc.waitFor();
         sop("Exit Value  is : "+exitValue);
    catch(Exception e)
    e.printStackTrace();
    }Test.ksh
      export -- application realated paths..
      nohup  abc.exe 1> test.log 2>&1;
      $1
      exit.By running the above java class , i am getting exit Value: 139 and log file test.log of 0 bytes.
    when i am running the same command (/usr/bin/ksh test.ksh satish) manually, it's calling abc.exe file successfully
    and able generate the logs properly.
    Pls let us know where exactly i am stuck..
    Thanks in advance,
    Regards,
    Satish

    Hi Sabre,
    As per the guidelines provided by the article, i had done below changes..
    InputStream is = null;
    InputStreamReader iStreamReader = null;
    BufferedReader bReader = null;
    String line = null;
    try{
    String fileName ="test.ksh";
    String argValue ="satish"; // value passed to the script
    String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
    Process proc = Runtime.getRuntime().exec(exeParam);
    is = proc.getErrorStream();
    iStreamReader = new InputStreamReader(is);
    bReader = new BufferedReader(iStreamReader);
    System.out.println("<ERROR>");
    while((line = bReader.readLine()) != null)
    System.out.println("Error is : "+line);
    System.out.println("</ERROR>");
    int exitValue = proc.waitFor();
    sop("Exit Value is : "+exitValue);
    catch(Exception e)
    e.printStackTrace();
    Now , it's showing something like..
    <ERROR>
    </ERROR>

  • Example: Executing a shell script from java

    Hi. There are many other posts in the forums related to executing a unix script from java, but I wanted to post another example that I thought might be helpful...
    The key thing to executing the script is to include the -c switch for the sh command. This tells the sh command that you are passing a string to be interpreted as input. Without this switch, the script does not execute as you'd expect it to. Also, use a string array to pass each part of the sh command.
    Here is a working sample class, along with a test script to execute it:
    public class TestShellScript {
    public static void main(String[] args)
    String[] chmod = {"chmod","777","testscript1"};
    String[] runscript = {"sh","-c","./testscript1 > jdata.out"};
    Runtime rtime = Runtime.getRuntime();
    try
    rtime.exec(chmod); // Set the authorities for testing
    rtime.exec(runscript); // Run the script with redirection
    catch (IOException e)
    e.printStackTrace();
    rtime = null;
    Here is a test script to wrap the java call:
    #!/bin/sh
    cd /<your script dir>
    export -s CLASSPATH=/<your jar dir>/TestShellScript.jar
    export -s PATH=/<your script dir>:/usr/bin
    java TestShellScript
    - Hope this helps.

    I don't know exactly but the code written below is working fine try the same with your code .Even with your code instead running the code with
    " ./<filename> ",if you execute it with "sh <filename>" command without changing the mode of the file it is executing properly.
    import java.io.*;
    import java.util.*;
    public class ScriptBuilder
    public ScriptBuilder()
    public void writeScript() throws java.io.IOException
    FileWriter writer = new FileWriter(new File("test_script"));
    writer.write("#! /bin/sh\n");
    writer.write("ll>/home/faiyaz/javaprac/checkll");
    writer.flush();
    writer.close();
    Runtime rt= Runtime.getRuntime();
    rt.exec("chmod 777 test_script");
    rt.exec("./test_script");
    } public static void main (String[] args)throws java.io.IOException
    ScriptBuilder sb = new ScriptBuilder();
    sb.writeScript();
    }

  • Executing a shell script from a java program

    Hi,
    I'm facing a problem while executing a shell script from a jsp page.
    I'm using exec() function.
    It's working fine for single statement scripts.But if the script consists of any database processing and some other processing statements,it's not returning the correct exit status of the process.
    Will u please help me in this.
    If there is any other ways to execute a shell script from a jsp page other than Runtime.exec().If so let me know.
    Thanks in advance.

    I think this shud workMaybe - but it is wrong! Why do you create aReader
    and then read bytes which are turned into a String
    without worrying about whether or not the bytes area
    String and without worrying about the character
    encoding if the bytes do represent characters and
    without worrying about how many bytes wereactually
    read.
    Also, both you and the OP should read, digest and
    follow the advice given in
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-
    traps.htmlI dont care if it is wrong. This code works for me.
    We are here to solve problems not to find which post
    is wrong.It is wrong! You are posting bad advice that is very wrong! It may work for you but it is wrong in general! WRONG WRONG WRONG.
    If you have a solution then post it I did post a solution! The reference I gave will explain to you and the OP exactly how it should be done.
    rather then
    posting rude comments.I was not rude! I was explaining just some of what was wrong!

  • Executing a shell script from a jsp page

    Hi,
    I'm facing a problem while executing a shell script from a jsp page.
    I'm using Runtime.exec() function.
    It's working fine for single statement scripts.But if the script consists of any database processing and some other processing statements,it's not returning the correct exit status of the process.
    Will u please help me in this.
    If there is any other ways to execute a shell script from a jsp page other than Runtime.exec() like RMI etc,.If so let me know.
    Thanks in advance.

    Hello,
    It's hard to help you but what you can do is listening to the outputs of your script, you should read the output stream and error stream and send them to the default console.
    Check this excellent article : http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
    Best regards,
    Olivier.

  • Invoking a bash shell script from Java code

    Hi All
    I am trying to invoke a Bash shell script using java code. The arguments required are "source wmGenPatch <source dir> <destination dir> no_reverse.
    in the code I have specified the arguments considering the cannonical paths of the files as the code may run on Unix or windows platform.
    I am getting a error while invoking Runtime.getRuntime().exec(args). The error is as follows :
    "The Error Occurred is: CreateProcess: source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=2"
    It seems that error=2 indicates that the 'file not found' exception. But i can see the directories referred to in the error at place in the workspace.
    Kindly advice.
    Thanks in advance.

    Hi All
    I am pretty new to invoking bash shell scripts from java and not sure if i am progressing in right direction.
    The piece of code tried by me is as follows
    try {
                   currentDir = f.getCanonicalPath();
              } catch (IOException e) {
              if (currentDir.contains("/")) {
                   separator = "/";
              } else {
                   separator = "\\";
              String args[] = new String[7];
              args[0] = "/bin/sh";
              args[1] = "-c";
              args[2] = "source";
              args[3] = currentDir + separator + "DiffEngineScripts" + separator
                        + "v4a02" + separator + "wmGenPatch";
              args[4] = sourceFileAdd;
              args[5] = destFileAdd;
              if (isReverseDeltaRequired) {
                   args[6] = "reverse";
              } else {
                   args[6] = "no_reverse";
              try {
                   Process xyz = Runtime.getRuntime().exec(args);                              
                   InputStream result = xyz.getInputStream();
                   InputStreamReader isr = new InputStreamReader(result);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ( (line = br.readLine()) != null)
                        System.out.println(line);
                   int exitVal = xyz.waitFor();
                   System.out.println("Leaving Testrun.java");
              } catch (Throwable t) {
                   t.printStackTrace();               
    and on running the same i am getting Java.io.IOException with the stack trace
    java.io.IOException: CreateProcess: \bin\sh -c source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=3
    kindly advice
    Thanks in advance

  • Invoking unix shell scripts from java?

    Hi,
    could someone explain to me how one wuld invoke unix shell scripts from java.
    Also, could you invoke Visual Basic scripts from java.
    Finally, could you do this from an EJB?
    thanks for any help....
    sudu

    I just posted a snippet of this solution in the topic about widows commands chech it out it works just fine for unix shell scripts.
    --Ian                                                                                                                                                                                                                                                                                       

  • Error while trying to execute a unix shell script from java program

    Hi
    I have written a program to execute a unix shell script in a remote machine. I am using J2ssh libraries to estabilish the session connection with the remote box.The program is successfully able to connect and authenticate with the box.
    The runtime .exec() is been implemented to execute the shell script.I have given below the code snippet.
    try {
         File file_location = new File("/usr/bin/");
         String file_location1 = "/opt/app/Hyperion/scripts/daily";
         String a_mib_name = "test.sh";
         String cmd[] = new String[] {"/usr/bin/bash", file_location1, a_mib_name};
         Runtime rtime = Runtime.getRuntime();
         Process p = rtime.exec(cmd, null, file_location);
    System.out.println( "Connected to the server1" );
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    while(line !=null)
    System.out.println(line);
    line = br.readLine();
    br.close();
    p.getErrorStream ().close ();
    p.getOutputStream().close();
    int retVal = p.waitFor();
    System.out.println("wait " + retVal);
    //session.executeCommand("ls");
    catch (IOException ex) {
    I get an error message
    Connected to the server
    java.io.IOException: Cannot run program "/usr/bin/bash" (in directory "\usr\bin"
    ): CreateProcess error=3, The system cannot find the path specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at SftpConnect.main(SftpConnect.java:143)
    Caused by: java.io.IOException: CreateProcess error=3, The system cannot find th
    e path specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    I am sure of the file path where the bash.sh and test.sh are located.
    Am i missing something? Any help would be greatly appreciated.
    Thanks
    Senthil

    Hi, I am using a simple program to connect to a RMI server and execute shell script. I use the Runtime.exec aommand to do the same.
    The script is sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul
    The script when run from the server, gives no errors. But when ran using rthe above method in java, gives errors as follows,
    Mycode:
    String command = "/bin/sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);
    int exitVal = proc.exitValue();
    System.out.println("Process exitValue: " + exitVal);
    java.io.IOException: CreateProcess: /bin/sh /tmp/pub/alka/test.sh /tmp/pub/alka/abc/xyz/ul ul error=3
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at DecryptTest.main(DecryptTest.java:18)
    Can anyone please help

  • Calling Shell Script From Java

    Hi i have a shell script which calls the ant command.How do i call this shell script from jdk 1.5. I used p = runtime.exec( filename) but it threw an IOException saying cannot execute. How do i call this from my java program which runs on the redhat linux box.Please Help

    Possibility:
    It does not have execute permissions - Either grant them by chmod or use the command as sh <script-name>
    Rich

  • Invoke a shell script from java

    hi all
    does anyone know how to invoke a shell script from your java program?
    thanks
    udam

    Use Runtime.exec(), make sure your script is executable, and make sure it starts with something like #!/bin/sh

  • Sending arguments to shell script from Java program

    Hi,
    I am invoking a shell script within a Java program by runtime command.But I need to pass a variable to the shell script from the Java program!!!
    Please help me!!!
    Thanks!!!

    You can set environment variables as the second argument to Runtime.exec(). You can pass argument on the command line. So, what sort of argument do you want to pass?

  • How to run unix shell script from java web applet

    hi all
    i have created one java applet. my apache web server is on unix server.
    i have created one shell script in same directory where my .class and .htm files reside...
    how to run this shell script from applet? it should search this .sh file on server and not on the client browser machine...
    thanks in advance

    I suppose you could make the shell script into a CGI, configure the server to execute CGIs, and then make the applet open the URL of that CGI.

  • Execute a shell script from inside PL procedure

    Oracle 9205 on Red Hat Enterprise Linux 3.
    Is there any way to execute an O.S. shell script from inside a PL/SQL procedure?
    This is, that PL_SQL procedure evaluate a situation and if the condition is true, it calls and execute an O.S. shell script.

    PL/SQL procedures do not support any native calls to the OS; however, you can code calls to external procedures or JAVA procedures to perform tasks on the OS.
    Prior to these two methods any of the following packages dbms_alert, dbms_pipe, or utl_file could be combined with a daemon type program to issue OS commands, run shell scripts, etc....
    There is a writeup on metalink with examples.
    HTH -- Mark D Powell --

  • How can I call unix shell script from database using triggers

    Hi everyone,
    can anybody help me to solve my problem.
    we have one table and records are getting inserted into table.
    when the record is inserted with 'C',I need to fetch that record-id which is primary key and then by passing that id as an argument I need to execute a shell script which is there in Unix using triggers.
    please note DB and Scripts are in different servers.

    4159efc6-cffb-4496-bd1a-68859f6ce776 wrote:
    Hi everyone,
    can anybody help me to solve my problem.
    we have one table and records are getting inserted into table.
    when the record is inserted with 'C',I need to fetch that record-id which is primary key and then by passing that id as an argument I need to execute a shell script which is there in Unix using triggers.
    please note DB and Scripts are in different servers.
    PL/SQL can only interact with objects on the local DB Server.
    PL/SQL can initiate OS local script via any of the following mechanisms: EXTERNAL PROCEDURE, JAVA, DBMS_SCHEDULER
    The local script then will need to launch the remote script.

Maybe you are looking for

  • Error message in Bridge CS6 -- how to fix?

    I'm getting an error message in Bridge CS6. I'm trying to create a Journal with Filmstrip with 42 items.  The creation process stops after several photos -- 32 last time -- and I get an error messgae saying "Gallery creation stopped because of unknow

  • Error: SAP Netweaver 2004s SR1 on Linux( Fedora Core 9)

    i had an error shootup message at PHASE 94/99(  when i was installing Netweaver usages types AS ABAP,AS JAVA, BI JAVA,DI,EP,MI and PI the error message looks like this ..i beive there is problem with JAVA..? WARNING 2008-05-26 10:32:56 Execution of t

  • How to remove a dynamic offset from an integrated signal?

    Hello everyone, I need a big help from you. First of all I dont know whether it is the right forums' section, in the case I am sorry. I acquire a signal from a laser vibrometer (velocity) and, in order to obtain the displacement, I integrate the sign

  • HT204382 Error when saving a video from smilebox. Quick Time Error?

    I tried to save a video "name.mov" from smilebox. Once directly after installing quicktime pro it works, now no more. Recording the video is stopped before end of video. Any solutions?

  • How to create compitable libraries

    Hi, We have some applications dependant on our libraries. All the applications are dynamically linked.(*.so). Whenever there is a change in class variables,addition of new methods in or libraries all the applications must recompile. Can we build libr