tee and exit status

前端 未结 8 1873
礼貌的吻别
礼貌的吻别 2021-02-07 10:43

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

相关标签:
8条回答
  • 2021-02-07 11:25
    { mycommand --foo --bar 2>&1; ret=$?; } | tee -a some.log; (exit $ret)
    
    0 讨论(0)
  • 2021-02-07 11:26

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

    0 讨论(0)
  • 2021-02-07 11:27

    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;
    
    0 讨论(0)
  • 2021-02-07 11:28

    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,

    0 讨论(0)
  • 2021-02-07 11:29

    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
    
    0 讨论(0)
  • 2021-02-07 11:34

    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.
    0 讨论(0)
提交回复
热议问题