Gonnix Gonnix - 2 months ago 5
Bash Question

How to get exit status, standard output and standard error streams of Java application in shell script?

My shell script needs to get the result (exit status) and capture the log output from Java application, which writes to its standard output and standard error streas.

To get the status code of the Java application I can do this:

RESULT=$(java <My app>)


To get its output streams I can do this:

$java <My app> >> Mylog.txt 2>&1 || true;


But I can't find a way to get both.

Answer

You can use the tee command to both append your output and keep writing to stdout:

RESULT_STDOUT=$($java classname | tee -a Mylog.txt)

Here, the -a asks tee to append to Mylog.txt, if possible.

I'm not sure why you need the true there, so I excluded that. The main problem here is how to preserve the error log. If you do 2>&1 it will become part of Mylog.txt but also of the result. If storing the error log in a separate file is sufficient for you, you can redirect it with

RESULT_STDOUT=$($java classname 2>> Mylog.error.txt | tee -a Mylog.txt)

EDIT: The exit status you can get via $PIPESTATUS, as @Raedwald pointed out: bash: pipe output AND capture exit status. The above solution captures stdout as RESULT_STDOUT only.