Simon
Simon

Reputation: 13

Incomplete output about Java Runtime.getRuntime().exec(command)

I want to build an app like Jenkins terminal: jenkins terminal snapshot

And I use Java Runtime.getRuntime().exec(command) to execute the command, find out that the output is incomplete.

textshell.sh:

# textshell.sh
echo "wwwwwww";
sleep 2
ls

For example: When I execute textshell.sh in my mac terminalsh -x testshell.sh , output :

+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh

but when I execute by java Java Runtime.getRuntime().exec("sh -x testshell.sh") , output:

wwwwwww
testshell.sh

the shell args -x seems useless

How can I fix it?

Upvotes: 1

Views: 300

Answers (1)

DuncG
DuncG

Reputation: 15196

As @Joachim Sauer points out you are not reading STDERR so miss the lines of echo output from the set -x output. Adjust your code to access the process.getErrorStream() as well.

Alternatively you can switch to ProcessBuilder if wanting to read the error stream merged with the output:

String[]cmd = new String[]{"sh", "-x", "testshell.sh"}
ProcessBuilder pb = new ProcessBuilder(cmd);

// THIS MERGES STDERR>STDOUT:
pb.redirectErrorStream(true);

// EITHER send all output to a file here:
Path stdout = Path.of("mergedio.txt");
pb.redirectOutput(stdout.toFile());

Process p = pb.start();

// OR consume your STDOUT p.getInputStream() here as before:

int rc = p.waitFor();

System.out.println("STDOUT: \""+Files.readString(stdout)+'"');

Upvotes: 1

Related Questions