我知道如何使用tee将aaa.sh的输出(标准输出)写入bbb。退出,同时仍然显示在终端中:

./aaa.sh | tee bbb.out

我现在如何将标准错误写入一个名为ccc的文件。退出,同时仍然显示它?


当前回答

简单:

./aaa.sh 2>&1 | tee -a log

这只是简单地将标准错误重定向到标准输出,因此tee对日志和屏幕都进行回显。也许我遗漏了一些东西,因为其他的解看起来很复杂。

注意:从Bash版本4开始,你可以使用|&作为2>和1 |的缩写:

./aaa.sh |& tee -a log

其他回答

发送到标准错误(STDERR)的编译错误可以通过以下方法重定向或保存到文件:

Bash:

gcc temp.c &> error.log

C shell (csh)

% gcc temp.c |& tee error.log

参见:如何将编译/构建错误重定向到文件?

以下将适用于KornShell (ksh),其中进程替代不可用,

# create a combined (standard input and standard output) collector
exec 3 <> combined.log

# stream standard error instead of standard output to tee, while draining all standard output to the collector
./aaa.sh 2>&1 1>&3 | tee -a stderr.log 1>&3

# cleanup collector
exec 3>&-

这里真正的技巧是2>&1 1>&3的序列,在我们的例子中,它将标准错误重定向到标准输出,并将标准输出重定向到文件描述符3。此时,标准误差和标准输出还没有结合起来。

实际上,标准错误(作为标准输入)被传递给tee, tee在那里将日志记录到stderr.log,并重定向到文件描述符3。

文件描述符3一直将其记录到combined。log。因此,combine .log包含标准输出和标准错误。

这可能对人们通过谷歌找到这个有用。只需取消您想要尝试的示例的注释。当然,可以随意重命名输出文件。

#!/bin/bash

STATUSFILE=x.out
LOGFILE=x.log

### All output to screen
### Do nothing, this is the default


### All Output to one file, nothing to the screen
#exec > ${LOGFILE} 2>&1


### All output to one file and all output to the screen
#exec > >(tee ${LOGFILE}) 2>&1


### All output to one file, STDOUT to the screen
#exec > >(tee -a ${LOGFILE}) 2> >(tee -a ${LOGFILE} >/dev/null)


### All output to one file, STDERR to the screen
### Note you need both of these lines for this to work
#exec 3>&1
#exec > >(tee -a ${LOGFILE} >/dev/null) 2> >(tee -a ${LOGFILE} >&3)


### STDOUT to STATUSFILE, stderr to LOGFILE, nothing to the screen
#exec > ${STATUSFILE} 2>${LOGFILE}


### STDOUT to STATUSFILE, stderr to LOGFILE and all output to the screen
#exec > >(tee ${STATUSFILE}) 2> >(tee ${LOGFILE} >&2)


### STDOUT to STATUSFILE and screen, STDERR to LOGFILE
#exec > >(tee ${STATUSFILE}) 2>${LOGFILE}


### STDOUT to STATUSFILE, STDERR to LOGFILE and screen
#exec > ${STATUSFILE} 2> >(tee ${LOGFILE} >&2)


echo "This is a test"
ls -l sdgshgswogswghthb_this_file_will_not_exist_so_we_get_output_to_stderr_aronkjegralhfaff
ls -l ${0}

换句话说,您希望将stdout输送到一个过滤器(tee bbb.out),将stderr输送到另一个过滤器(tee cc.out)。没有标准的方法将stdout以外的任何内容输送到另一个命令中,但是可以通过处理文件描述符来解决这个问题。

{ { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2

参见如何grep标准错误流(stderr)?和什么时候你会使用一个额外的文件描述符?

在bash(和ksh和zsh)中,而不是在其他POSIX shell中,如dash,你可以使用进程替换:

./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out)

注意,在bash中,该命令在./aaa.sh完成后立即返回,即使tee命令仍在执行(ksh和zsh确实在等待子进程)。如果您执行。/aaa.sh > >(tee bbb.out) 2> >(tee ccc.out);process_logs bbb。ccc.out。在这种情况下,使用文件描述符杂耍或ksh/zsh代替。

简单:

./aaa.sh 2>&1 | tee -a log

这只是简单地将标准错误重定向到标准输出,因此tee对日志和屏幕都进行回显。也许我遗漏了一些东西,因为其他的解看起来很复杂。

注意:从Bash版本4开始,你可以使用|&作为2>和1 |的缩写:

./aaa.sh |& tee -a log