1

I have the following bash script java_debug to log all java executions (standard and error console):

#! /bin/bash
echo param1: $1
echo param2: $2

(java HelloWorld "$@" 2>&1 ) | tee /tmp/log.txt

I run it:

$ java_debug v1 "v2 with space"
param1: v1
param2: v2 wirh space
Error: Could not find or load main class HelloWorld

$ echo $?
0

in this example, java cannot find the HelloWorld class, and so it shows an error. However, the error is lost in $? (we get 0 instead of 1) because of the subshell and/or the pipe.

I need that java_debug returns the same exit code as the java execution

How to fix this script?

note: I could use the script command instead of 2>&1 | tee, but unfortunately the implementation of the script command changes in different systems (the script parameters are not the same in redhat than in OSX).

note: I am aware that bash is an horrible language and it should not be used; but I have no choice in this case.

David Portabella
  • 12,390
  • 27
  • 101
  • 182

1 Answers1

5

found answer here: Get exit code from subshell through the pipes

in my case:

#! /bin/bash
echo param1: $1
echo param2: $2

(java HelloWorld "$@" 2>&1 ) | tee /tmp/log.txt
exit ${PIPESTATUS[0]}
Community
  • 1
  • 1
David Portabella
  • 12,390
  • 27
  • 101
  • 182