打印 STDOUT/STDERR 并将它们写入 Bash 中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4739418/
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-17 23:18:49  来源:igfitidea点击:

Print STDOUT/STDERR and write them to a file in Bash?

linuxbashstdoutstderrio-redirection

提问by Naftuli Kay

Is there a way to have Bash redirect STDOUT/STDERR to a file yet still print them out to the terminal as well?

有没有办法让 Bash 将 STDOUT/STDERR 重定向到文件,但仍将它们打印到终端?

回答by SiegeX

This will redirect both STDOUT and STDERR to the same file:

这会将 STDOUT 和 STDERR 重定向到同一个文件:

some_command 2>&1 | tee file.log

Example

例子

$ touch foo; ls foo asfdsafsadf 2>&1 | tee file.log
ls: asfdsafsadf: No such file or directory
foo
$ cat file.log
ls: asfdsafsadf: No such file or directory
foo

回答by I82Much

Use the teecommand.

使用tee命令。

$ echo "hi" | tee output.txt
hi
[unix]$ ls
output.txt
[unix]$ cat output.txt 
hi