Bash 将输出重定向到 tty 和文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25645946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:17:38  来源:igfitidea点击:

Bash redirect output to tty and file

bashstdout

提问by Dejwi

I'm trying to log some part of script execution. Logs should be displayed at second tty, and also written to a log file.

我正在尝试记录脚本执行的某些部分。日志应显示在第二个 tty,并写入日志文件。

I can do it with a simple:

我可以用一个简单的方法来做到:

echo "Hello log" > /dev/tty2
echo "Hello log" > /var/log/my_logs

But it is very uncomfortable. I could also redirect echo to a particular place:

但是很不舒服。我还可以将 echo 重定向到特定位置:

exec 1<>/var/log/my_logs
exec 2>&1

But how can I redirect STDOUT to both /dev/tty2 and /var/log/my_logs at once?

但是我怎样才能同时将 STDOUT 重定向到 /dev/tty2 和 /var/log/my_logs 呢?

回答by chepner

Use tee.

使用tee.

echo "Hello log" | tee /dev/tty2 /var/log/my_logs > /dev/null

(The final redirection is to prevent the output from appearing to standard output as well. You could also use echo "Hello log" | tee /dev/tty2 > /var/log/my_logs; there's no real difference between the two. teejust writes it standard input to both standard output and one or more named files.)

(最后的重定向是为了防止输出也出现在标准输出中。您也可以使用echo "Hello log" | tee /dev/tty2 > /var/log/my_logs; 两者之间没有真正的区别。tee只需将其标准输入写入标准输出和一个或多个命名文件。)

To redirect all of standard output to the pair, use a process substitution with exec.

要将所有标准输出重定向到该对,请使用带有exec.

exec > >(tee /dev/tty2 /var/log/my_logs)