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

Similar Messages

  • 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                                                                                                                                                                                                                                                                                       

  • 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 a shell script from JSP

    Hi,
    I am trying to invoke a shell script from within my JSP. I need to pass a few parameters to this shell script also. The shell script then returns a string value to the JSP. Any ideas, how to acheive this? I would appreciate any help.
    Thanks,
    Fauzia

    implement a method somewhere that uses Runtime.exec() internally. see here:
    http://java.sun.com/j2se/1.3/docs/api/index.html
    robert

  • 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()

  • Invoking Shell Script from JAVA Stored procedure

    I am trying to invoke shell script using Java Stored procedure.
    When I run my java class outside of oracle using oracle user
    account it works but as soon as i load it into database and try
    to inovoke that class using PL/SQL wrapper it runs java class
    but is not able to invoke the shell script. Any ideas would be
    greatly appreciated.

    Pleass search the forums for "runtime" as there are many threads and examples already posted.

  • Invoking shell script from java

    I hava a shell script on a unixbox which needs to be invoked through a web application. How do I do it? What is the method to login,and then invoke the shell script? Also, should the password be directly mentioned in the java file?

    Pleass search the forums for "runtime" as there are many threads and examples already posted.

  • 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?

  • 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>

  • 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

  • How to invoke a shell script using java

    Hi
    I am trying to invoke a shell script(unix) using java and I have tryied to load the shell using exec(cmd) and then trying to execute the shell.
    But it is not working.
    Can you please guide me on this matter.

    Hi I am facing the same problem
    I want to call a shell script through java in linux system of course.
    I am using the following section of code .
    public class LinuxServer {
         public static void main(String args[]){
              Runtime r = Runtime.getRuntime(); //get runtime information
              try
              Process Child = r.exec("/usr/bin/ksh") ; //execute command
              BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(Child.getOutputStream()));
              outCommand.write("/opt/jboss-4.0.0/test1.sh");
              outCommand.flush();
              try
              Child.waitFor(); //wait for command to complete
              catch(InterruptedException e)
              { //handle waitFor failure
              System.out.println("ERROR: waitFor failure");
              System.exit(10); //exit application with exit code 10
              catch(IOException e)
              { //handle exec failure
              System.out.println("ERROR: exec failure"+e);
              System.exit(11); //exit application with exit code 11
    But when I am compiling and running this script in the linux system,
    Its giving the following error.
    Exception in thread "main" java.lang.NoClassDefFoundError: while resolving class: LinuxServer
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)
    at JvThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)
    at JvRunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)
    at __gcj_personality_v0 (/opt/jboss-4.0.0/java.version=1.4.2)
    at __libc_start_main (/lib/tls/libc-2.3.4.so)
    at JvRegisterClasses (/opt/jboss-4.0.0/java.version=1.4.2)
    Caused by: java.lang.ClassNotFoundException: java.lang.StringBuilder not found in [file:/usr/local/staf/lib/JSTAF.jar, file:/usr/local/staf/samples/demo/STAFDemo.jar, file:/home/db2inst4/sandip/staf/lib/JSTAF.jar, file:/home/db2inst4/sandip/staf/samples/demo/STAFDemo.jar, file:/usr/share/java/libgcj-3.4.3.jar, file:./, core:/]
    at java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/libgcj.so.5.0.0)
    at JvFindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at JvBytecodeVerifier.verify_instructions_0() (/usr/lib/libgcj.so.5.0.0)
    at JvVerifyMethod(_Jv_InterpMethod) (/usr/lib/libgcj.so.5.0.0)
    at JvPrepareClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at JvWaitForState(java.lang.Class, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.linkClass0(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    ...9 more
    Pls help

  • 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.

  • Passing argument to shell script from java program

    str="/bin/sh -c /root/PWAppSh/StartSH.sh";
    p = rt.getRuntime().exec(str);
    above is the code snippet of java program for calling the shellscript
    when i pass a argument to the shell script from my java program it wont get accepted in shell script as an input
    when i do following changes in above code it wont work :---
    str="/bin/sh -c /root/PWAppSh/StartSH.sh para1 para2 para3 ";
    p = rt.getRuntime().exec(str);
    para1,para2 and para3 wont get as argument for the shell script
    how this can be done
    thanks
    reply "ARGENT"

    Argent.
    Read this:
    Navigate yourself around pitfalls related to the Runtime.exec() method

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

  • 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

Maybe you are looking for

  • Crystal Report Printing in GBP Instead of Euro's

    Hi Guys, I need a crystal report I have done to print in Euro's, however it is printing out in GBP and making the automatic conversion. Can you tell me how to force it to print in Euros which is the default for this particular BP and the sales docume

  • How to delete iMessages on multiple devices.

    When iMessage is activated on multiple devices with the same Apple ID, will deleting the message on one device delete it on all others?

  • P35 Neo: Freezes on Boot Screen HELP!

    Hi, I need help. I took some of my old parts and bought some new ones to make a cheap computer for my dad. The mobo I used, used to be in my old pc, and ran great with an intel e8400 in it. I put together today: P35 Neo Intel e3400 Corsair XMS2 2GB (

  • LabVIEW.ex​e - applicatio​n error

    Hi. I'm trying to use CIN to up-down flip a two dimensional array passed from LabVIEW.  Everything seems to work fine when I run the .vi (flipper.vi).  However, when I run another .vi (save_data.vi) that uses the flipper subroutine, it crashes LabVIE

  • Troulbe in measuremen​t quadrature encoder with 6601

    Hi, Thanks for Ross's help.But I cannot differ 6601's x4 mode from other counter/timer counting mode. In measurement position, what difference between them. And I just want to know whether my application viable. We are trying to measure position with