Java exec() of UNIX shell script

I have a java application that uses:
p = Runtime.getRuntime().exec( cmdLine);
to execute a UNIX shell script, for example:
#!/bin/ksh
. /export/pc112477/freeware/work1/wsEnv
export PATH=/opt/sfw/bin:/usr/ccs/bin:/usr/bin:/usr/ucb:$PATH
cd /export/pc112477/freeware/work1/usr/src/pkgdefs/SFWnmap
/usr/ccs/bin/make -e ROOT=$ROOT install
RESULT=$?
if [ $RESULT = 0 ]
then
echo "Package source"
cd /export/pc112477/freeware/work1/usr/src/pkgdefs/SFWnmapS
/usr/ccs/bin/make -e ROOT=$ROOT install
RESULT=$?
fi
exit $RESULT
Some times the running of the script locks up depending on how much work the script has to, eg. if the make calls pkgmk for a small package it runs okay but if its a large package it locks up in pkgmk.
The script itself works okay if run directly
Does anyone have any ideas on why this locks up and how I could stop it doing it.
Thanks

For anyone who stumbles across this and needs an answer:
To empty the standard error and output, you need to use getErrorStream() and getInputStream() on the Process object created when you execed your command. Create new InputStreamReaders with the streams from the process, then wrap those with BufferedReaders and read each line with a while loop. This is the basic thing you need to do:
try{
Process proc = Runtime.getRuntime().exec(command);
InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader errReader = new BufferedReader(isr);
String line;
while((line = errReader.readLine()) != null)
<do something with each line of error>
} //end try
catch(<errors>) {
<do something with errors>
} //end catch
What you really should do is put the stream handling in a separate class that extends Thread, create an instance for the error and output streams, and start each one. There is a class called StreamGobbler that does this sort of thing. Look at http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html to find out more about it and read a detailed explanation of different problems with exec().

Similar Messages

  • 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

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

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

  • Running Unix Shell scripts through Java

    How to run Unix shell scripts through Java program ?

    Use:
    Process p = Runtime.getRuntime().exec("sh script.sh");Then you can use:
    p.getOutputStream and read the output of your program.

  • Exit status running java classpath in a unix shell script

    I'm new to putting java into unix scripts. I have a java classpath running inside of a unix shell script. During my testing it will error with java.io.FileNotFoundException error, which I know why that is, but when I set in my unix shell script this to see the right exit status of success/fail, it always shows a 0 for success when that isn't really the case. Below is the two lines I have set to capture the exit status and just display that exit status for now.
    notifycode=$?
    echo $notifycode
    I have these 2 lines above on a line right below my java command in my unix shell script. How can I get my unix shell script to show the right exit status if the java classpath command fails? Thanks for any help.

    That's Java code, it says "End this Java application and send return code 1 back to the shell". As for how the shell gets the return code from the application, that's a question about your shell and not about Java programming, no?

  • Running UNIX shell scripts from a Java app

    I want to build a GUI in Java as a front-end to a collection of UNIX shell scripts I have written. Is this possible?

    It is possible, but it kinda defeats the purpose of shell scripts no?

  • 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                                                                                                                                                                                                                                                                                       

  • Executing java from unix shell script

    Hi, I am trying to execute java program from a unix shell script and the program has a command line parameter. I have tried in ways like
    /opt/java1.4/bin/java CollExtractLoadProcess /home/inbox/archive/file_name
    /opt/java1.4/bin/java CollExtractLoadProcess "/home/inbox/archive/file_name"
    /opt/java1.4/bin/java CollExtractLoadProcess '/home/inbox/archive/file_name'
    /opt/java1.4/bin/java CollExtractLoadProcess file_name
    No matter how I execute it gives me the following error
    Exception in thread "main" java.lang.ClassFormatError: CollExtractLoadProcess (C
    ode segment has wrong length)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
    3)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
    Could someone please let me know what is the correct way of doing this?
    Thanks.

    Sounds like you either have a corrupt class file or you're using an older version of the JVM to try to execute classe that were compiled for a newer version.

  • How to execute unix shell script in webdynpro?

    hi all,
      We have some iquirement of executing script in unix.If anyone know How to execute unix shell script in webdynpro?
    best regard
    reefish

    Ree,
    1. Find SSH client for windows, then execute SSH with Runtime.exec() on local host with arguments like remote host, auth, command to execute etc.
    2. Get SSH client in Java and execute SSH commands on remote host using pure Java API.
    Don't ask me for links, Google works today, I checked this
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Can i call unix shell script from B2B callout.

    Hi,
    We had a requirement to invoke a unix shell script from B2B callout implemented class. Here is the code in implementation class:
    public void execute(CalloutContext context,List input,List output)
    throws CalloutDomainException, CalloutSystemException {
    try {
    CalloutMessage cmIn = (CalloutMessage)input.get(0);
    FileOutputStream fos = null;
    String inputFile = "/home/orasoad/digitalsign/input/test.txt";
    String outputFile = "/home/orasoad/digitalsign/output/test.txt.gpg";
    File outFile = new File(inputFile);
    String str =cmIn.getBodyAsString();
    fos = new FileOutputStream(outFile);
    Writer out = new OutputStreamWriter(fos);
    out.write(str);
    out.close();
    String shellFile = "/home/orasoad/digitalsign/dg.sh";
    String cmd[] = new String[] { shellFile, inputFile, outputFile };
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(cmd);
    int i = pr.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    StringBuffer sb = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {              
    sb.append(line);
    CalloutMessage cmOut = new CalloutMessage(sb.toString());
    output.add(cmOut);
    } catch (Exception e) {
    throw new CalloutDomainException(e);
    We were able to execute the unix shell script from standalone java class with same code. But some how it is not working as expected while invoking the B2B java callout.
    Is it possible to invoke unix shell script from B2B callout?
    Please give inputs.
    Regards,

    Though it's not a good idea to invoke shell scripts from java callout but technically it will work.
    But some how it is not working as expected while invoking the B2B java callout.What is not working as expected? Any error in the log (server-diagnostic.log or server.out)?
    Regards,
    Anuj

  • How can i call a Stored Procedure procedure from Unix shell script

    Hi All,
    I want to call a Strored PL-SQL Procedure through Unix shell script.
    Can any body help me with this.
    Regards,
    Saurabh

    I prefer a seperate script like the other poster mentioned. However, most shells can use a 'here' document as well ...
    sqlplus uid/pwd <<END
    exec myproc
    exit
    ENDRichard

  • Sending email attachments using unix shell script

    hi
    I want to send report generated my spooled file as attachment using unix shell script.
    Can somebody help me out ?
    many thanks

    thanks a tonn it worked.
    but i have another issue is it possible to add names in CC also ?
    Also here is my code which spools the output of SP to a txt file. the File name is generated dynamically.
    as shown below:
    I need to send this generated file as attachement.
    how do I do this? Here the shell script
    =========================================================
    #!/bin/sh
    ORA_USER=scott
    ORA_PWD=tiger
    #Get the input parameter
    if [ ! "$1" ]; then
    STR="NULL"
    else
    STR="'"$1"'"
    fi
    #echo "exec pkg1($STR);"
    #Connecting to oracle
    sqlplus -s <<EOF
    $ORA_USER/$[email protected]
    ---sql plus enviornment settings
    set linesize 160
    set pagesize 60
    set serveroutput on size 1000000 for wra
    set feedback off
    set termout off
    column dcol new_value mydate noprint
    select to_char(sysdate,'YYYYMMDDHH24MISS') dcol from dual;
    spool &mydate.report.txt
    exec pkg1($STR);
    spool off
    EOF
    exit
    =========================================================
    the file name will take sysdate as name so that every time a new file will be generated.
    this file I need to send as attachment.
    null

  • Calling stored procedure from unix shell script

    Hello,
    I am facing a problem while calling a stored procedure from UNIX shell script. I want to return a output variable from the stored procedure to the UNIX environment.
    Here is the code-
    #!/bin/sh
    OUTPUT=`sqlplus cmag/magnum@dw <<ENDOFSQL
    set serveroutput on;
    var prd_out varchar2(100);
    exec create_pm_window(:prd_out);
    exit;
    ENDOFSQL`
    echo " output is - $OUTPUT"
    The problem is :prd_out is not getting copied to shell variable OUTPUT.
    I have a dbms_output.put_line in the stored proc create_pm_window and I can see that prd_out is getting populated.
    Any help is really appreciated.
    Thanks'
    Rakhee

    First step :
    make sure the PL/SQL works as expected.
    Does the following display the expected output executed from SQL*Plus ?
    set serverout on
    declare
    prd_out varchar2(100);
    begin
    create_pm_window(prd_out);
    dbms_output.put_line('output is '||prd_out);
    end;
    I don't have your procedure, but using a dummy procedure like :
    Scott@my10g SQL>create procedure foo(p_out in out varchar2)   
      2  is
      3  begin
      4  select 'Hello '||instance_name into p_out from v$instance;
      5  end;
      6  /
    Procedure created. and a toto.sh script as :OUTPUT=`sqlplus -s scott/tiger <<EOF
    set pages 0 lines 120 trimout on trimspool on tab off echo off verify off feed off serverout on
    var mavar varchar2(100);
    exec foo(:mavar);
    print mavar;
    exit;
    EOF`
    echo "OUT = ${OUTPUT}"
    exitIt works fine :[oracle@Nicosa-oel ~]$ ./toto.sh
    OUT = Hello my10g

  • Unable to pass parameter in oracle procedure through unix shell script

    Hi Experts,
    I have oracle procedure where in I have to pass the value of procedure parameter through unix script.
    Follwoing is the sample procedure which i tried to exceute from the unix.
    Procedure:
    create or replace procedure OWNER.PRC_TESTING_OWNER(OWNER IN VARCHAR2) AS
    sql_stmt varchar2(1000) := NULL;
    v_count number := 0;
    v_owner varchar2(100) := owner;
    begin
    sql_stmt:='select count(1) from '||v_owner||'.EMP@infodb where rownum<=10';
    execute immediate sql_stmt into v_count;
    DBMS_OUTPUT.PUT_LINE(sql_stmt);
    DBMS_OUTPUT.PUT_LINE(v_count);
    END;The script which I used is:
    Unix
    #!/bin/ksh
    parm=$1
    echo start
    sqlplus -s scott@DEV/tiger <<EOF >>result_1.txt
    set serveroutput on;
    select '$parm' from dual;
    exec owner.PRC_TESTING_OWNER('$parm');
    EOFThe script is working fine that is i am able to pass to parameter value through unix shell script. :)
    But if I want to pass the value of the owner in cursor , I am unable to pass this value through unix.
    Following the procedure which i am trying to implement.
    create or replace procedure OWNER.PRC_TESTING_OWNER(OWNER IN VARCHAR2) IS
    v_owner varchar2(100) := owner;
    CURSOR main_cur IS 
      select
      i.ROWID  rid ,
      emp_name,
      deptid
      from v_owner.employee;
    CURSOR subset_cur(c_deptid NUMBER ) IS
        SELECT *
          FROM v_owner.DEPT d
          where  d.dept_id=c_deptid;
    --##main loop     
    FOR i IN main_cur LOOP
          FOR j IN subset_cur(i.deptid) LOOP     
    BEGIN
    insert into v_owner.RESULT_TABLE
    END;
    END LOOP;
    END LOOP;How can i pass parameter value of the stored procedure through unix script(that is "owner" in this case), when these parameter value is
    used in cursor? :(
    Can anybody help me regarding the same?
    Thanks in Advance !! :D

    It's not the parameter in the cursor that is the problem, it's that you are trying to use static SQL for something that won't be known until run time (the owner of the table).
    You would need to use something like ...
    declare
       l_owner        varchar2(30) := 'SCOTT';
       l_ref_cursor   sys_refcursor;  
       type l_ename_tab is table of scott.emp.ename%type;
       l_ename_array  l_ename_tab;
    begin
       open l_ref_cursor for
          'select ename
          from ' || l_owner || '.emp';
       loop
          fetch l_ref_cursor bulk collect into l_ename_array limit 10;
          exit when l_ename_array.COUNT = 0;
          for x in 1 .. l_ename_array.count
          loop
             dbms_output.put_line(l_ename_array(x));
          end loop;
       end loop;
       close l_ref_cursor;
    end;
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01

Maybe you are looking for

  • Error while updating the Human task

    When I try to update my Human task the following error is occuring in JDeveloper and I can't save my changes, any help will be appreciable. thank you. Uncaught exception java.lang.NullPointerException o.bpel.services.workflow.verification.impl.TaskCo

  • Paper jams when being faxed on my HP Officejet Pro 8600 Plus e-All-in-O​ne Printer - N911g

    When I go to send a fax, the paper goes in until about half way then the right side begins to wrinkle the paper and jams up.  I have tried several things to fix it but no luck.

  • To retrieve taxation details

    hello everyone.       I have a scenario  where i have to retrieve and display BED  and VAT values from database.      Where i am finding the same fields and tables for the above two values!. Can anyone please explain the procedure to retrieve those v

  • Audit Vault 10.3 Console - Internal Error on Pages/Tabs Accessing Port 1158

    Hello Audit Vaulters! I wonder if any one has encountered this problem we are having right now. We are using the default port 1158 for the AV console. It looks like it has stopped working properly. This port is accessed by the "Audit Policy" tab when

  • New extensions on an existing Forms10g application

    Hello Form Guru's, My customer is considering upgrading a Forms6i (generated with Designer and Headstart) application to a new 10g environment. We consider to follow the Oracle strategy (Tools Statement of Direction) to upgrade to the latest version