发球和退出状态

pac*_*nga 15 unix shell tee

是否有"tee"的替代方法,它捕获正在执行的命令的STDOUT/STDERR,并以与处理的命令相同的退出状态退出.如下:

eet -a some.log -- mycommand --foo --bar
Run Code Online (Sandbox Code Playgroud)

其中"eet"是"tee":)的假想替代品(-a表示追加, - 分隔捕获的命令)不应该很难破解这样的命令但是它可能已经存在并且我不知道它?

谢谢.

Vil*_*ari 22

这适用于bash:

(
  set -o pipefail
  mycommand --foo --bar | tee some.log
)
Run Code Online (Sandbox Code Playgroud)

括号用于限制pipefail对一个命令的影响.

从bash(1)手册页:

除非pipefail启用该选项,否则管道的返回状态是最后一个命令的退出状态.如果pipefail启用,则管道的返回状态是以非零状态退出的最后(最右侧)命令的值,如果所有命令都成功退出,则返回零.


pac*_*nga 9

在这里偶然发现了几个有趣的解决方案http://www.perlmonks.org/?node_id=597613.

1)bash中有$ PIPESTATUS变量:

   false | tee /dev/null
   [ $PIPESTATUS -eq 0 ] || exit $PIPESTATUS
Run Code Online (Sandbox Code Playgroud)

2)perl中最简单的"eet"原型可能如下所示:

   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;
Run Code Online (Sandbox Code Playgroud)


eph*_*ent 5

这是一个eet.适用于每个Bash,我可以从2.05b到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 "$@"
Run Code Online (Sandbox Code Playgroud)

(pipefail并且$PIPESTATUS很好,但我记得它们是在3.1或其附近引入的.)