tee 命令主要作用是接收标准输入内容,将数据写到标准输出以及文件,来源于水管工在连接多根水管时使用的 T 型分流器,就如上图展示的那样形象展示了它的功能。
基本用法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
root@master:/home/uphie# tee --help
Usage: tee [OPTION]... [FILE]...
Copy standard input to each FILE, and also to standard output.
-a, --append append to the given FILEs, do not overwrite
-i, --ignore-interrupts ignore interrupt signals
-p diagnose errors writing to non pipes
--output-error[=MODE] set behavior on write error. See MODE below
--help display this help and exit
--version output version information and exit
MODE determines behavior with write errors on the outputs:
'warn' diagnose errors writing to any output
'warn-nopipe' diagnose errors writing to any output not a pipe
'exit' exit on error writing to any output
'exit-nopipe' exit on error writing to any output not a pipe
The default MODE for the -p option is 'warn-nopipe'.
The default operation when --output-error is not specified, is to
exit immediately on error writing to a pipe, and diagnose errors
writing to non pipe outputs.
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation <https://www.gnu.org/software/coreutils/tee>
or available locally via: info '(coreutils) tee invocation'
将内容写到文件中
接收标准输入到文件中:
1
2
3
4
5
6
7
8
9
root@master:/home/uphie# tee myinput.txt <<EOF
> hello world
> hello uphie
> EOF
hello world
hello uphie
root@master:/home/uphie# cat myinput.txt
hello world
hello uphie
如果 myinput.txt 之前存在的话,会覆盖内容,如果想追加内容,可以使用 -a 选项:
1
2
3
4
5
6
7
8
root@master:/home/uphie# tee -a myinput.txt <<EOF
> hello linux
> EOF
hello linux
root@master:/home/uphie# cat myinput.txt
hello world
hello uphie
hello linux
标准输出也可以作为输入内容,将内容写到文件中:
1
2
3
4
root@master:/home/uphie# ll *.yaml | tee yamlfile.txt
-rw-r--r-- 1 root root 993 Jan 16 11:21 kubeadm-config.yaml
root@master:/home/uphie# cat yamlfile.txt
-rw-r--r-- 1 root root 993 Jan 16 11:21 kubeadm-config.yaml
输出到多个文件
冗余记录ping baidu 的结果:
1
2
3
4
5
6
root@master:/home/uphie# ping baidu.com | tee pingbaidu.txt pingbaidu.txt.bak
PING baidu.com (110.242.68.66) 56(84) bytes of data.
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=1 ttl=128 time=50.4 ms
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=2 ttl=128 time=48.4 ms
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=3 ttl=128 time=49.0 ms
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=4 ttl=128 time=48.0 ms
输出到文件但隐藏输出
1
root@master:/home/uphie# ll | tee files.txt >/dev/null