我知道如何使用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>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

在我的例子中,一个脚本正在运行命令,同时将stdout和stderr重定向到一个文件,类似于:

cmd > log 2>&1

我需要更新它,以便在出现故障时,根据错误消息采取一些操作。当然,我可以删除dup 2>&1并从脚本中捕获stderr,但是错误消息不会进入日志文件以供参考。虽然从lhunath接受的答案应该做同样的事情,它将stdout和stderr重定向到不同的文件,这不是我想要的,但它帮助我提出了我需要的确切解决方案:

(cmd 2> >(tee /dev/stderr)) > log

通过上述操作,log将同时拥有标准输出和标准错误的副本,并且我可以从脚本中捕获标准错误,而不必担心标准错误。

感谢lhunath在POSIX中的回答。

下面是我在POSIX中需要的一个更复杂的情况:

# Start script main() function
# - We redirect standard output to file_out AND terminal
# - We redirect standard error to file_err, file_out AND terminal
# - Terminal and file_out have both standard output and standard error, while file_err only holds standard error

main() {
    # my main function
}

log_path="/my_temp_dir"
pfout_fifo="${log_path:-/tmp}/pfout_fifo.$$"
pferr_fifo="${log_path:-/tmp}/pferr_fifo.$$"

mkfifo "$pfout_fifo" "$pferr_fifo"
trap 'rm "$pfout_fifo" "$pferr_fifo"' EXIT

tee -a "file_out" < "$pfout_fifo" &
    tee -a "file_err" < "$pferr_fifo" >>"$pfout_fifo" &
    main "$@" >"$pfout_fifo" 2>"$pferr_fifo"; exit

如果使用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)

换句话说,您希望将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代替。