tee命令详解

tee命令示意图tee过滤器用来想多个目标发送输出的内容。如果用于管道的话,他可以将输出复制一份到文件,兵复制另外一份到屏幕上(或一些其他的程序)。

1
ll /etc | nl | tee /temp//ll.out

在以上例子中,从ll输出可以捕获到/temp/ll.out文件中,并且同样在屏幕上显示出来。

tee [ -a ] [ -i ] [檔案 … ]

参数:

檔案 一个或多个档案,能够接收 tee-d 的输出。

Flags:

-a 追加到目标文件而不是覆盖
-i 忽略中断。

tee命令读取标准输入,把这些内容同时输出到标准输出和(多个)文件中(read from standard input and write to standard output and files. Copy standard input to each FILE, and also to standard output. If a FILE is -, copy again to standard output.)。在info tee中说道:tee命令可以重定向标准输出到多个文件(tee': Redirect output to multiple files. Thetee’ command copies standard input to standard output and also to any files given as arguments. This is useful when you want not only to send some data down a pipe, but also to save a copy.)。要注意的是:在使用管道线时,前一个命令的标准错误输出不会被tee读取。

常用参数

格式:tee

只输出到标准输出,因为没有指定文件嘛。

格式:tee file

输出到标准输出的同时,保存到文件file中。如果文件不存在,则创建;如果已经存在,则覆盖之。(If a file being written to does not already exist, it is created. If a file being written to already exists, the data it previously
contained is overwritten unless the `-a’ option is used.)

格式:tee -a file

输出到标准输出的同时,追加到文件file中。如果文件不存在,则创建;如果已经存在,就在末尾追加内容,而不是覆盖。

格式:tee -

输出到标准输出两次。(A FILE of -' causestee’ to send another copy of input to standard output, but this is typically not that useful as the copies are interleaved.)

格式:tee file1 file2 -

输出到标准输出两次,同时保存到file1和file2中。

使用tee命令把标准错误输出也保存到文件

1
2
3
4
5
6
7
8
9
10
11
12
[root@web ~]# ls "*"
ls: *: 没有那个文件或目录
[root@web ~]# ls "*" | tee -
ls: *: 没有那个文件或目录
[root@web ~]# ls "*" | tee ls.txt
ls: *: 没有那个文件或目录
[root@web ~]# cat ls.txt
[root@web ~]# ls "*" 2>&1 | tee ls.txt
ls: *: 没有那个文件或目录
[root@web ~]# cat ls.txt
ls: *: 没有那个文件或目录
[root@web ~]#