Piping command output to tee but also save exit code of command
You can set the pipefail
shell option option on to get the behavior you want.
From the Bash Reference Manual:
The exit status of a pipeline is the exit status of the last command in the pipeline, unless the
pipefail
option is enabled (see The Set Builtin). Ifpipefail
is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.
Example:
$ false | tee /dev/null ; echo $?
0
$ set -o pipefail
$ false | tee /dev/null ; echo $?
1
To restore the original pipe setting:
$ set +o pipefail
You could run the mvn command and cache the exit code... I use the "false" command for my example.
$ { false ; echo $? > /tmp/false.status ; } | tee $logfile
$ cat /tmp/false.status
1
That way you can use the status file content to make further decisions.
I'm curious now whether there is a more eloquent way to accomplish this.
Since you're running bash
, you can use its $PIPESTATUS variable instead of $?
:
mvn clean install $@ | tee $logfile
echo ${PIPESTATUS[0]}