Solved

how to call shellscript from java program

Posted on 2004-04-28
10
680 Views
Last Modified: 2012-06-21
how to call shell script from java program and i need to pass some parameters also to that script.it's urgent
0
Comment
Question by:vsita
10 Comments
 
LVL 9

Expert Comment

by:mmuruganandam
Comment Utility
use

Runtime runtime = Runtime.getRuntime();

String[] cmd = {"aaa.sh", "param1", "param2", .....};
Process p = runtime.exec(cmd);

This way, you can execute the shell script from Java.

If you want to see the output of the process

then
InputStream in = process.getInputStream();
in.read();

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Pass a String array of arguments to this:


package net.proteanit.process;

import java.io.*;

/**
 *  Runs a program
 *
 * @author     CEHJ
 * @created    23 February 2004
 */
public class CommandRunner {

      private int returnValue = Integer.MIN_VALUE;



      /**
       *  Gets the returnValue attribute of the CommandRunner object
       *
       * @return    The returnValue value
       */
      public int getReturnValue() {
            return returnValue;
      }



      /**
       *  The main program for the CommandRunner class
       *  For testing only
       *
       * @param  args  The command line arguments
       */
      public static void main(String[] args) {
            new CommandRunner().run(args);
      }





      /**
       *  Description of the Method
       *
       * @param  args  Description of the Parameter
       */

      /**
       *  Main processing method for the CommandRunner object
       *
       * @param  args  Description of the Parameter
       */
      public void run(String[] args) {

            try {

                  if (args.length < 1) {
                        System.out.println("Usage: java CommandRunner <command string>");
                        System.exit(-1);
                  }
                  Process pro = null;
                  if (args.length > 1) {
                        pro = Runtime.getRuntime().exec(args);
                  }
                  else {
                        pro = Runtime.getRuntime().exec(args[0]);
                  }
                  InputStream error = pro.getErrorStream();
                  InputStream output = pro.getInputStream();
                  Thread err = new Thread(new OutErrReader(error));
                  Thread out = new Thread(new OutErrReader(output));
                  out.start();
                  err.start();
                  returnValue = pro.waitFor();
            }
            catch (java.io.IOException e) {
                  e.printStackTrace();
            }
            catch (java.lang.InterruptedException e) {
                  e.printStackTrace();
            }

      }


      /**
       *  Description of the Class
       *
       * @author     Administrator
       * @created    23 February 2004
       */
      class OutErrReader implements Runnable {
            InputStream is;


            /**
             *Constructor for the OutErrReader object
             *
             * @param  is  Description of the Parameter
             */
            public OutErrReader(InputStream is) {
                  this.is = is;
            }


            /**
             *  Main processing method for the OutErrReader object
             */
            public void run() {
                  try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(is));
                        String temp = null;
                        while ((temp = in.readLine()) != null) {
                              System.out.println(temp);
                        }
                        is.close();
                  }
                  catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }
}
0
 

Author Comment

by:vsita
Comment Utility
my java program is

Runtime runtime = Runtime.getRuntime();
String[] cmd = {"run.sh", "5"};
Process p = runtime.exec(cmd);


insdie run.sh i am accesing that value "5" and want to echo that value at the command prompt and also write to some file.

my run.sh is

code=$1
echo  code
code > inputs.txt

whether this code is correct or not.
i am not able to get the value at the command prompt and also value is not written to the file
0
 
LVL 9

Expert Comment

by:mmuruganandam
Comment Utility
you won't get anything at command prompt...


Runtime runtime = Runtime.getRuntime();
String[] cmd = {"run.sh", "5"};
Process p = runtime.exec(cmd);

InputStream in = p.getInputStream();

int ch ;

while ((ch = in.read()) != -1)
{
       System.out.println((char)ch);
}


Add this code, you can see the echo part in the command prompt ....
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
The last line should read:

echo code > inputs.txt

;JOOP!
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Using the program above:

CommandRunner.run(new String[] { "sh", "run.sh", "5" });
0
 
LVL 9

Accepted Solution

by:
mmuruganandam earned 125 total points
Comment Utility
InputStream in = p.getInputStream();

int ch ;

while ((ch = in.read()) != -1)
{
       System.out.println((char)ch);
}

This is the part of code, which is used to get the output of the launched process....

So if you read the input stream of the process and prints out the contents, then you can able to see the echo part in your command prompt.


Regards,
Muruga
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(assuming the name of the executable of your shell interpreter is 'sh' )
0
 
LVL 9

Expert Comment

by:mmuruganandam
Comment Utility
>> echo code > inputs.txt

This will move the "5" to inputs.txt


You won't find anything in the command prompt then...

change that to

echo code
0
 
LVL 9

Expert Comment

by:mmuruganandam
Comment Utility
thanx :-)
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now