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>

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

  • 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                                                                                                                                                                                                                                                                                       

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

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

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

  • 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

  • Java.io.filepermission error while executing a batch file from java prog

    Hi,
    i want run a java program which executes a batch file, both are in a jar file. while am trying this using webstart it shows error:access denied java.io.filepermission <<ALL FILES>>execute. why this happens how to rectify this.
    By
    Vinod

    Clearly, it would be a security vulnerability to be able to do such a thing from the web w/o user granting trust to the application.
    Java Web Start applications run in the Java SE secure sandbox unless they have been granted all-permissions by the user:
    1.) sign all jar files.
    2.) add <security><all-permissions/></security> to the jnlp file.
    The user would then be prompted to grant trust to the applications.
    /Andy

  • Passing Null Characters from Unix Shell Script to Java Program

    Hi Experts,
    Facing an issue with a shell script....
    The shell script has 10 input parameters....
    1st Parameter is a compiled Java program name(This can keep changing)
    Rest 9 are the parameters of the Java Program...
    The following piece of code is working when Test "a z" "b t" "" "" "" "" "" "" "" "" is hardcoded.
    lv_java_string=`java Test "a z" "b t" "" "" "" "" "" "" "" ""`
    The whole thing being dynamic.....
    But when I dynamically populate the same on to a parameter lv_java_param and then execute the same
    lv_java_string=`java $lv_java_param`
    if i echo $lv_java_param  its giving me Test "a z" "b t" "" "" "" "" "" "" "" ""  correctly
    Im facing some issue...... The issue is " is being treated as a parameter itself and the space between a and z is not taken into consideration and hence z is taken as the 2nd parameter
    Issue seems to be something like the precedence in which the above statement is executed, because of which "s are calculated/manipulated. Is it something like
    a) $lv_java_param is computed  first and then java $lv_java_param
    b) or java $lv_java_param is run on the fly......
    Any help is much appreciated.

    This forum is about Oracle *RDBMS*
    I don't see any question about Oracle RDBMS
    Please find a forum about Java.
    Sybrand Bakker
    Senior Oracle DBA

  • Command not found error while executing a shell script

    Hello,
    I am a newbie to linux.I am attaching the code which gives me following errors..
    error list:
    1. no such file or directory enviornemnt
    2. command not found
    3. ambiguous redirectline
    Script
    cd $HOME/wkdir
    rm /tmp/*.log
    # source environment
    . ./env
    # Run the install script to setup the database
    # Configure SH account
    sqlplus "/ as sysdba" <<! > /tmp/perflab_install.log 2>&1
    grant connect, resource, dba to SH;
    alter user sh account unlock;
    # create the fetch_n_rows procedure
    sqlplus "$PERFLAB_USER" <<! >> /tmp/perflab_install.log 2>&1
    drop index sales_time_bix;
    drop index sales_time_idx;
    create index sales_time_idx on sales(time_id) compute statistics;
    -- fetch_n_rows: fetches 'n' rows from the specified statement --
    CREATE OR REPLACE PROCEDURE fetch_n_rows(
    stmt VARCHAR,
    name VARCHAR,
    nexec NUMBER := 1,
    nrows NUMBER := 0,
    debug BOOLEAN := FALSE)
    IS
    -- Local variables
    curs INTEGER := null;
    rc INTEGER;
    nexec_it INTEGER := 0;
    nrows_it INTEGER;
    BEGIN
    dbms_application_info.set_module('DEMO', name);
    WHILE (nexec_it < nexec)
    LOOP
    curs := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE(curs, stmt, DBMS_SQL.NATIVE);
    rc := DBMS_SQL.EXECUTE(curs);
    nrows_it := 0;
    LOOP
    IF (dbms_sql.fetch_rows(curs) <= 0 OR (nrows <> 0 AND nrows_it = nrows
    THEN
    EXIT;
    ELSE IF (debug = TRUE)
    THEN
    DBMS_OUTPUT.PUT_LINE(nrows_it);
    END IF;
    END IF;
    nrows_it := nrows_it + 1;
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR(curs);
    nexec_it := nexec_it + 1;
    END LOOP;
    dbms_application_info.set_module(null, null);
    END fetch_n_rows;
    show errors
    # Start the workload
    . ./start_workload.sh > /tmp/setup_perflab.log 2>&1
    # Wait two minutes for workload to get going
    sleep 120
    # Modify snapshot interval
    sqlplus -s /NOLOG <<EOF >> /tmp/setup_perflab.log 2>&1
    connect / as sysdba
    set head on
    set feedback on;
    set pagesize 40
    rem -- event to allow setting very short Flushing interval
    alter session set events '13508 trace name context forever, level 1';
    rem -- change INTERVAL setting to 2 minutes
    rem -- change RETENTION setting to 6 hours (total of 180 snapshots)
    execute dbms_workload_repository.modify_snapshot_settings(interval => 2,-
    retention => 360);
    EOF
    Note : start_workload.sh is also in the same directory..
    Any help would be greatly appreciated.

    Please put your script between "code" format delimiters.
    http://wiki.oracle.com/page/Oracle+Discussion+Forums+FAQ
    You can add the line "set -x" at the beginning of your script to see at which line it fails? I suspect the . ./env line.

  • Error while Executing Unix Shell Commands Using Runtime clas

    I am trying to run the following code in java on unix machine to execute cat command.
    Runtime runtime = Runtime.getRuntime();
              try {
                   System.out.println("before catexecute");
                   Process process = runtime.exec("cat /export/home/shankerr/local.profile > /export/home/shankerr/local1.txt");
                   try {
                        if (process.waitFor() != 0) {
                        System.err.println("exit value = " +
                                  process.exitValue());
                        catch (InterruptedException e) {
                        System.err.println(e);
    But i get the following error on the console
    exit value = 2
    cat: cannot open >
    cat: cannot open /export/home/shankerr/local1.txt
    The same command if i run on unix console directly it creates a new file and copies the content into the new file local1.txt
    kindly help me on the same

    The redirection operator > along with stuff like pipe | history !$ etc. is interpreted by the shell, not by the cat program.
    When you do cat X > Ycat only sees the X. The rest is interpreted by the shell to redirect the cat program's stdout.
    However, when you Runtime.exec(), you don't have the shell, so cat sees X > Y as its arguments, and interprets them all as file names. Since there's no file named > you get the error.
    The solution is to first man cat on your system and see if it happens to have a -o or somesuch operator that lets it (rather than the shell) send its output to a file. If not, then you need to invoke a shell, and pass it cat and all of cat's args as the command to execute.
    Read the man pages for you shell of choice, but for bash, I believe you'd give Runtime.exec() something like /bin/bash -c 'cat X > Y'

  • Error when run UNIX Shell Script from PL/SQL

    when I run command.
    I got the error message, please anyone suggest me., what's problem?
    thanks in advance.
    modd
    exec shell('ls')
    ORA-06520: PL/SQL: Error loading external library
    ORA-06522: '/modd/test/shell.so' is not a valid load module: Bad magic number
    ORA-06512: at "modd.SHELL", line 0
    ORA-06512: at line 1

    Hi
    Try to add
    (ENVS=EXTPROC_DLLS=ANY) to listener.ora
    eg:
    SID_LIST_LISTENER =
    (SID_LIST =
    (SID_DESC =
    (SID_NAME = PLSExtProc)
    (ORACLE_HOME = /oracle/product/9.2)
    (ENVS=EXTPROC_DLLS=ANY)
    (PROGRAM = extproc)
    lajos

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

Maybe you are looking for