我知道如何使用tee将aaa.sh的输出(标准输出)写入bbb。退出,同时仍然显示在终端中:
./aaa.sh | tee bbb.out
我现在如何将标准错误写入一个名为ccc的文件。退出,同时仍然显示它?
我知道如何使用tee将aaa.sh的输出(标准输出)写入bbb。退出,同时仍然显示在终端中:
./aaa.sh | tee bbb.out
我现在如何将标准错误写入一个名为ccc的文件。退出,同时仍然显示它?
当前回答
发送到标准错误(STDERR)的编译错误可以通过以下方法重定向或保存到文件:
Bash:
gcc temp.c &> error.log
C shell (csh)
% gcc temp.c |& tee error.log
参见:如何将编译/构建错误重定向到文件?
其他回答
简单:
./aaa.sh 2>&1 | tee -a log
这只是简单地将标准错误重定向到标准输出,因此tee对日志和屏幕都进行回显。也许我遗漏了一些东西,因为其他的解看起来很复杂。
注意:从Bash版本4开始,你可以使用|&作为2>和1 |的缩写:
./aaa.sh |& tee -a log
将标准错误重定向到一个文件,将标准输出显示到屏幕上,并将标准输出保存到一个文件:
./aaa.sh 2>ccc.out | tee ./bbb.out
要在屏幕上显示标准错误和标准输出,并将它们保存到文件中,您可以使用Bash的I/O重定向:
#!/bin/bash
# Create a new file descriptor 4, pointed at the file
# which will receive standard error.
exec 4<>ccc.out
# Also print the contents of this file to screen.
tail -f ccc.out &
# Run the command; tee standard output as normal, and send standard error
# to our file descriptor 4.
./aaa.sh 2>&4 | tee bbb.out
# Clean up: Close file descriptor 4 and kill tail -f.
exec 4>&-
kill %1
我假设您仍然希望在终端上看到标准错误和标准输出。你可以选择Josh Kelley的答案,但我发现在后台保持一个尾巴,输出你的日志文件非常笨拙。注意,你需要保留一个额外的文件描述符,然后通过杀死它来进行清理,从技术上讲,应该在陷阱'…'中进行清理退出。
有一个更好的方法可以做到这一点,并且您已经发现了它:tee。
只是,它不仅仅用于标准输出,还有一个用于标准输出和一个用于标准误差。你将如何做到这一点?进程替换和文件重定向:
command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
让我们分开来解释:
> >(..)
>(…)(进程替换)创建一个FIFO并让tee监听它。然后,它使用>(文件重定向)将命令的标准输出重定向到您的第一个tee正在侦听的FIFO。
第二种情况也一样:
2> >(tee -a stderr.log >&2)
我们再次使用进程替换来创建一个tee进程,该进程从标准输入读取数据并将其转储到stderr.log中。Tee将它的输入输出回标准输出,但由于它的输入是我们的标准误差,我们希望将Tee的标准输出重定向到我们的标准误差。然后我们使用文件重定向将命令的标准错误重定向到FIFO的输入(tee的标准输入)。
参见输入和输出
进程替换是选择Bash而不是sh (POSIX或Bourne)作为shell的额外好处之一。
在sh中,你必须手动操作:
out="${TMPDIR:-/tmp}/out.$$" err="${TMPDIR:-/tmp}/err.$$"
mkfifo "$out" "$err"
trap 'rm "$out" "$err"' EXIT
tee -a stdout.log < "$out" &
tee -a stderr.log < "$err" >&2 &
command >"$out" 2>"$err"
以下将适用于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包含标准输出和标准错误。
如果使用Bash:
# Redirect standard out and standard error separately
% cmd >stdout-redirect 2>stderr-redirect
# Redirect standard error and out together
% cmd >stdout-redirect 2>&1
# Merge standard error with standard out and pipe
% cmd 2>&1 |cmd2
信用(不回答从我的头顶)在这里:Re: bash: stderr & more(管道为stderr)