Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a interactive shell script using java Runtime?

I am wondering is there any way to execute following shell script, which waits for user input using java's Runtime class?

#!/bin/bash

echo "Please enter your name:"
read name
echo "Welcome $name"

I am using following java code to do this task but it just shows blank console.

public class TestShellScript {
public static void main(String[] args) {

        File wd = new File("/mnt/client/");
           System.out.println("Working Directory: " +wd);
           Process proc = null;

           try {
               proc = Runtime.getRuntime().exec("sudo ./test.sh", null, wd);

           } catch (Exception e) {
             e.printStackTrace();
             }


}

}

Thing is when I execute above program, I believed it will execute a shell script and that shell script will wait for user input, but it just prints current directory and then exits. Is there any way to do this or it is not possible at all in java?

Thanks in advance

like image 815
Rahul Borkar Avatar asked Mar 29 '12 14:03

Rahul Borkar


People also ask

Can Java execute shell commands?

Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.

What is runtime getRuntime () exec?

In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.

How do I run a terminal command in Java?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.


2 Answers

The reason it prints the current dir and exits is because your java app exits. You need to add a (threaded) listener to the input and error streams of your created process, and you'll probably want to add a printStream to the process's output stream

example:



            proc = Runtime.getRuntime().exec(cmds);
            PrintStream pw = new PrintStream(proc.getOutputStream());
            FetcherListener fl = new FetcherListener() {

                @Override
                public void fetchedMore(byte[] buf, int start, int end) {
                    textOut.println(new String(buf, start, end - start));
                }

                @Override
                public void fetchedAll(byte[] buf) {
                }           
            };
            IOUtils.loadDataASync(proc.getInputStream(), fl);
            IOUtils.loadDataASync(proc.getErrorStream(), fl);
            String home = System.getProperty("user.home");
            //System.out.println("home: " + home);
            String profile = IOUtils.loadTextFile(new File(home + "/.profile"));
            pw.println(profile);
            pw.flush();

To run this, you will need to download my sourceforge project: http://tus.sourceforge.net/ but hopefully the code snippet is instructive enough that you can just adapt to J2SE and whatever else you are using.

like image 76
ControlAltDel Avatar answered Nov 15 '22 00:11

ControlAltDel


If you use a Java ProcessBuilder you should be able to get the Input, Error and Output streams of the Process you create.

These streams can be used to get information coming out of the process (like prompts for input) but they can also be written to to put information into the process directly too. For instance:

InputStream stdout = process.getInputStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));

String line;
while(true){
    line = reader.readLine();
    //...

That'll get you the output from the process directly. I've not done it myself, but I'm pretty sure that process.getOutputStream() gives you something that can be written to directly to send input to the process.

like image 45
mtrc Avatar answered Nov 14 '22 23:11

mtrc