Search code examples
unixshelltee

'tee' and exit status


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?


Solution

  • 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.)