Solved

how to call shellscript from java program

Posted on 2004-04-28
10
682 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
ID: 10937440
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
ID: 10937566
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
ID: 10937634
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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10937645
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
ID: 10937646
The last line should read:

echo code > inputs.txt

;JOOP!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10937647
Using the program above:

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

Accepted Solution

by:
mmuruganandam earned 125 total points
ID: 10937653
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
ID: 10937659
(assuming the name of the executable of your shell interpreter is 'sh' )
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10937663
>> 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
ID: 10937786
thanx :-)
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
java 8 lambda expresssions exception handling 3 91
micro services spring boot application error 3 196
servlet example 11 40
Error in @AspectJ Based AOP with Spring 2 13
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to implement Singleton Design Pattern in Java.

809 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