Java Runtime.getRuntime()。exec(command)に関する不完全な出力

Oct 28 2020

Jenkinsターミナルのようなアプリを作成したい:

そしてRuntime.getRuntime().exec(command)、Javaを使用してコマンドを実行すると、出力が不完全であることがわかります。

textshell.sh:

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

例:Macターミナルsh -x testshell.sh でtextshell.shを実行すると、次のように出力されます。

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

しかし、JavaJava Runtime.getRuntime().exec("sh -x testshell.sh") で実行すると、次のように出力されます。

wwwwwww
testshell.sh

シェル引数-xは役に立たないようです

どうすれば修正できますか?

回答

1 DuncG Oct 28 2020 at 13:35

@Joachim Sauerが指摘しているように、STDERRを読み取っていないので、出力からのエコー出力の行を見逃してset -xください。process.getErrorStream()同様にアクセスするようにコードを調整します。

またはProcessBuilder、出力とマージされたエラーストリームを読み取りたい場合に切り替えることができます。

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)+'"');