sriram
sriram

Reputation: 9032

Executing a shell scripts always returns null in Java

I have a shell script file called test.sh in the home directory ~. I want to execute the shell file using java. I use the following code:

Runtime runtime = Runtime.getRuntime();
        Process process = null;
        String cmd[] = {"/bin/bash","~/test.sh"};
        String[] env = {"PATH=/bin:/usr/bin/"};

        try
        {
            process = runtime.exec(cmd,env);
            process.waitFor();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();

            String line = reader.readLine();
            stringBuilder.append(line);

            System.out.println("The token is " + stringBuilder.toString() );

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

When I try to execute the following program, I get null as result like:

The token is null

where I'm making the mistake?

Edit:

test.sh has only

echo "Hello"

Upvotes: 0

Views: 546

Answers (1)

Eric Woodruff
Eric Woodruff

Reputation: 6410

You need to read from the stream while the process is alive. It doesn't make sense to access getInputStream after waitFor() returns because the process had died by then. You should start a thread to read getInputStream().

Something like:

process = runtime.exec(cmd,env);

final BufferedReader reader = new BufferedReader(new InputStreamReader (process.getInputStream()));
final StringBuilder stringBuilder = new StringBuilder();

new Thread () {
    public void run () {
        String line = reader.readLine();
        stringBuilder.append(line);
    }
}.start ();
process.waitFor();

Upvotes: 1

Related Questions