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.

Similar Messages

  • Running a shell script through java

    Hi all,
    I have a simple question here.
    How can I run a shell script through java and put the text output into a string.
    I'd be very grateful if you could show me sample code...
    Have a great day,
    Pesho

    Runtime.exec()
    There are plenty of examples. Read the following before continuing, however, as it will save alot of headaches:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

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

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

  • Running Shell scripts through JAva

    Hi,
    I tried to execute a Shell script through a Java program.
    The code I used is as below:
    import java.lang.*;
    import java.io.*;
    public class sys {
    public static void main(String[] args) {
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = { "chgpasswd" };
    try {
    Process child = rt.exec(callAndArgs);
    child.waitFor();
    System.out.println("Process exit code is: " + child.exitValue());
    catch(IOException e) {
    System.err.println( "IOException starting process!");
    catch(InterruptedException e) {
    System.err.println( "Interrupted waiting for process!");
    The "chgpasswd" shell script calls the "passwd" command of Unix.
    It threw out an IO exception.
    Then I gave the parameter as "./chgpasswd". It now gave an exit value of 255.
    The "chgpasswd" script exists in the same directory as the .class file.
    I checkd up the exit code reference...it says exit value of 255 could mean as exit code out of range........an exit code > 255....which unfortunately has no documentation, I guess.
    Can you help ?

    This is on a Unix platform, correct? Assuming so...
    If I remember correctly, exit codes can be greater than 255. To get the real exit code equates to something like: exitcode & 512 to obtain the real exit code.
    Make sure "chgpasswd" shell script has the execute permissions set. Additionally, make sure that the first line of the script (the magic line) has the appropriate shell/interpreter to execute specified. For example, if "chgpasswd" were a Bourne (sh) script, the first like would be:
    #!/bin/shFor perl, it may be something like:
    #!/usr/bin/perlIt needs to be the absolute path to the shell/interpreter is the point.

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

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

  • Run Unix command / Run Unix shell script from Forms9i

    Hi,
    I have a requirement to run Unix command and Unix shell scripts from Forms9i.
    I know HOST command cannot be used directly. I also know we can create some JAVA stored procedure to perform the task, but I don't want to create any JAVA stored procedure as there are some security concerns.
    Please point me towards any other way to achieve the same.
    I would really appreciate your help.
    Thanks,
    Kumar

    There is no reason why HOST can't be used. This is what it is for. As for using Java, it is not a stored procedure that you would be using, it would be imported Java (imported into the form).
    The best way to use the HOST command is to call a script (.sh) rather than calling a Unix command directly. This is because HOST will not pick up environment variables set at the system level. So the script would first need to set the necessary environment variables then call the desired commands.

  • Run a .sh script through JAVA ?

    Hi All,
    I have a shell script that basically gives me some status on my UNIX box. The name of the script is "scstat". But I need to parse the output shown by this script using JAVA.
    Does anybody know of any code or let me know the ways to implement this......your help is appreciated.
    Best Regards, sangita

    Test with string "ls -al", etc..
    import java.io.DataInputStream;
    import java.io.IOException;
    * Created on Apr 26, 2004
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author root
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class Execute {
         public static void main(String[] args) {
              Execute ex = new Execute();
              ex.execute("./scstat.sh" );     //if in current directory, need the path.
         /**Returns the output
          * @param string
         public static String execute(String string) {
              Process p;
              String s = null;
              try {
                   p = Runtime.getRuntime().exec(string);
              //     p.waitFor();
              DataInputStream in = new DataInputStream(p.getInputStream());
              while ( (s=in.readLine())  !=  null){
                   System.out.println(s);
              } catch (IOException e) {
                   e.printStackTrace();
              return s;
    }

  • How to run Unix Shell Scripts

    I hope someone knows Unix better me. I created a shell script to run some ap comp sci classes, and whenever I want to run the script, I'm forced to type:
    "./runMBS", while I want to just type "runMBS". Any suggestions will be nice.
    Thanks

    If you only type the name of a command (or script) the Unix shell only looks for those commands in the directories specified in the $PATH variable. If you provide a full or partial path to the command then the shell will run the command at that location... that's why including "./" in front of your shell script works... it tells the shell to run the command in the current directory (ie "./").
    You can either:
    - move your shell script to one of the directories specified in your $PATH variable
    or
    - add the directory containing your shell script to your $PATH
    To modify the $PATH so that it includes the directory your script resides in use something like this in your .bash_profile:
    <pre>
    PATH=$PATH:/path/to/scriptdir
    export PATH
    </pre>
    Although it's possible to include "./" in your PATH, it's not advisable and can present security problems. Read this explanation for more information.
    Steve

  • 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

  • How do i print parameters in shell script through java

    Hi,
    I am sorry if have posted this query in wrong thread!!!
    How do i print the parameter in shell script which are passed from java programm?
    i have tried in different ways.. but the actual param value is not printing when i execute the java programm
    java code is here
    import java.io.IOException;
    public class TestShell {
          * @param args
    public static void main(String[] args) {
             String inputFilePath=args[0];
              String inputFileName=args[1];
              String outputFileName=args[2];
              String outputFilePath=args[3];
              Runtime r = Runtime.getRuntime();
              String[] cmdArray = new String[]{"Test.sh",inputFilePath, inputFileName, outputFileName, outputFilePath};
              try {
                   r.exec(cmdArray);
                   System.out.println("Test.sh executed successfully.");
              } catch (IOException e) {
                   e.printStackTrace();
    }I need a shell script to print paramenters (inputFilePath, inputFileName, outputFileName, outputFilePath)
    Thanks,
    Jasmin

    user13836688 wrote:
    But my code is something look like thisWell unless I've completely lost my marbles (possible) or Java Runtime.exec() does something I've never heard of, I can't even see how that will execute. For a start, assignments in the Bourne shell take the form ofinfile = $inputFilename;orinfile = "inputFilename";not what you've got; and the first form would only work if you've set the appropriate environment variables.
    Are you sure you're not confusing this with a Javascript script?
    Winston
    Edited by: YoungWinston on Apr 18, 2011 12:51 PM
    And BTW, you don't need to put ';' at the end of each statement, unless there's more than one on a line.
    Edited by: YoungWinston on Apr 18, 2011 12:54 PM
    BTW2: 'printf "%d", inpath' also looks very dodgy, since 'inpath' is unlikely to be a number (in fact, it's unlikely to be anything).
    I think you might want to get a book on scripting.

  • Issues with running UNIX shell command from Java

    Here is my java class file:
    create or replace and compile java source named host as
    import java.lang.* ;
    public class Host
       public static void cmdTest()
            String cmd = "ps -ef | grep orcl" ;
            int rc = 0 ;
            int = runCmd(cmd) ;
       public static int runCmd(String str )
           Runtime rt = Runtime.getRuntime() ;
           int     rc = -1 ;
          try
                Process p = rt.exec(str) ;
                int bufSize = 4096 ;
                BufferedInputStream bis =
                    new BufferedInputStream(p.getInputStream(), bufSize) ;
                int len ;
                byte buffer[] = new byte[bufSize] ;
                // Log what the program spit out
                while ((len = bis.read(buffer, 0, bufSize)) != -1)
                    rc = p.waitFor() ;
            catch (Exception e)
                e.printStackTrace();
                rc = -1 ;
            finally
                return rc ;
    show errorsI can call runCmd directly from SQLPlus using an Oracle stored procedure and it runs like expected. I can see the returned output using dbms_java.set_output(1000000).
    But when I call cmdTest from SQLPlus using an Oracle stored procecdure it just hangs forever and I have to kill the session.
    Is there something I am missing in the cmdTest method?

    Jimmy,
    If you haven't already seen it, I think the following article may be of help:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Also a "finally" block should not contain a "return" statement:
    http://weblogs.java.net/blog/staufferjames/archive/2007/06/_dont_return_in.html
    Good Luck,
    Avi.

Maybe you are looking for