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

时间:2021-09-01 00:06:09

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重定向到一个文件,但仍然将它们打印到终端?

2 个解决方案

#1


16  

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

#2


3  

Use the tee command.

使用tee命令。

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

#1


16  

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

#2


3  

Use the tee command.

使用tee命令。

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