Abhishek Gangadhar
Abhishek Gangadhar

Reputation: 117

Executing a shell scripts that takes an input during execution with Java

I am trying to execute shell script in Java. I was able to achieve this in the following manner.

        ProcessBuilder pb = new ProcessBuilder("/path_to/my_script.sh");
        pb.redirectOutput(new File("/new_path/out.txt"));
        Process p = pb.start();
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

How would I give user input if the shell requires user input? How to implement this?

example: my_script.sh

#!/bin/bash
read -p "Enter your name : " name
echo "Hi, $name. Let us be friends!"

I need to give input of name through Java.

Upvotes: 1

Views: 642

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19305

EDIT following comments

    // writing to file
    String input = "Bob";
    try ( PrintWriter out = new PrintWriter( filename ) ) {
        out.print( input );
    }

    // redirecting input from file
    pb.redirectInput( new File( filename ) );
    pb.redirectOutput( Redirect.INHERIT );

Initial answer;

Depending on how it is launch, following may be sufficient

pb.redirectInput( Redirect.INHERIT );

However to see message, output should also be redirected to std out

pb.redirectOutput( Redirect.INHERIT );

and tee output maybe done from shell

exec 6>&1 1> >(tee /new_path/out.txt)  # start tee output to out.txt (save current output to file descriptor 6 for example)
...
exec >&6      # end to restore standard output and terminate tee process

Note about InterruptedException, it should not be catched and continue the program, but propagated until point where task is really finished.

Upvotes: 1

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5581

Hi You can do it like below:-

 String inputName = "blabla";
 String command = "/path_to/my_script.sh  " + inputName;
 Process p;
 try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

Now you have to modify your shell script like below:-

#!/bin/bash
#read -p "Enter your name : " name
name = $1
echo "Hi, $name. Let us be friends!"

Upvotes: 0

Related Questions