Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tee and exit status

Tags:

shell

unix

tee

Is there an alternative to tee which captures standard output and standard error of the command being executed and exits with the same exit status as the processed command?

Something like the following:

eet -a some.log -- mycommand --foo --bar

Where "eet" is an imaginary alternative to "tee" :) (-a means append and -- separates the captured command). It shouldn't be hard to hack such a command, but maybe it already exists and I'm not aware of it?

like image 620
pachanga Avatar asked Jun 12 '09 09:06

pachanga


2 Answers

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 the pipefail option is enabled. If pipefail 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.
like image 105
Ville Laurikari Avatar answered Oct 14 '22 07:10

Ville Laurikari


I stumbled upon a couple of interesting solutions at Capture Exit Code Using Pipe & Tee.

  1. There is the $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;
    
like image 26
pachanga Avatar answered Oct 14 '22 08:10

pachanga