is there an alternative to \"tee\" which captures STDOUT/STDERR of the command being executed and exits with the same exit status as the processed command. Something as followin
{ mycommand --foo --bar 2>&1; ret=$?; } | tee -a some.log; (exit $ret)
Here's an eet
. Works with every Bash I can get my hands on, from 2.05b to 4.0.
#!/bin/bash
tee_args=()
while [[ $# > 0 && $1 != -- ]]; do
tee_args=("${tee_args[@]}" "$1")
shift
done
shift
# now ${tee_args[*]} has the arguments before --,
# and $* has the arguments after --
# redirect standard out through a pipe to tee
exec | tee "${tee_args[@]}"
# do the *real* exec of the desired program
exec "$@"
(pipefail
and $PIPESTATUS
are nice, but I recall them being introduced in 3.1 or thereabouts.)
Stumbled upon a couple of interesting solutions here http://www.perlmonks.org/?node_id=597613.
1) There is $PIPESTATUS variable available in bash:
false | tee /dev/null
[ $PIPESTATUS -eq 0 ] || exit $PIPESTATUS
2) And the simplest prototype of "eet" in perl may look as follows:
open MAKE, "command 2>&1 |" or die;
open (LOGFILE, ">>some.log") or die;
while (<MAKE>) { print LOGFILE $_; print }
close MAKE; # to get $?
my $exit = $? >> 8;
close LOGFILE;
G'day,
Assuming bash or zsh,
my_command >>my_log 2>&1
N.B. Sequence of redirection and duplication of STDERR onto STDOUT is significant!
Edit: Oops. Didn't realise you wanted to see the output on screen as well. This will of course direct all output to the file my_log.
HTH
cheers,
Korn shell, ALL in 1 line:
foo; RET_VAL=$?; if test ${RET_VAL} != 0;then echo $RET_VAL; echo Error occurred!>/tmp/out.err;exit 2;fi |tee >>/tmp/out.err ; if test ${RET_VAL} != 0;then exit $RET_VAL;fi
This works with bash:
(
set -o pipefail
mycommand --foo --bar | tee some.log
)
The parentheses are there to limit the effect of pipefail to just the one command.
From the bash(1) man page:
The return status of a pipeline is the exit status of the last command, unless thepipefail
option is enabled. 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.