介绍
当用户在 Linux 交互式 shell 中执行命令时,输出将显示在文本终端中。但是,有一些方法可以使用连接在管道中的其他 shell 命令来更改此行为。
如何使用Linux tee命令?在本教程中,你将学习如何在 Linux 中使用 tee 命令来管理命令的输出。
先决条件
- 一个运行 Linux 的系统
- 访问命令行或终端
- 须藤权限
tee 命令在 Linux 中有什么作用?
该tee
命令读取标准输入 (stdin) 并将其写入标准输出 (stdout) 和一个或多个文件。tee
通常是管道的一部分,任何数量的命令都可以在它之前或之后。

注意:要在 Linux 中处理标准输入,你可以使用xargs 命令,该命令可以与其他命令结合使用。
Linux 中的 tee 命令示例
该tee
命令单独使用或与其他选项一起使用。如何使用Linux tee命令?以下部分列出了可用选项并提供了命令用法示例。
基本用途
Linux如何使用tee命令?tee
命令的基本语法是:
[command] | tee [options] [filename]
下面的示例演示了如何使用tee
来创建一个文件,该文件存储有关网络接口的信息,同时在终端中提供相同的输出:

该猫命令确认tee
成功地写输出ifconfig
到文件example.txt
:

如果用于命令的文件已经存在,则tee
覆盖文件的先前内容。
附加到给定文件
Linux tee命令用法示例:覆盖文件的内容是该tee
命令的默认行为。使用参数-a
(或--append
)将命令输出添加到文件末尾。
[command] | tee -a [filename]
例如,使用以下echo
命令将一行文本附加到文件中:

使用以下cat
命令确认添加成功:

写入多个文件
使用tee
后跟任意数量的文件将相同的输出写入每个文件:
[command] | tee [options] [filename1] [filename2]...
下面的示例显示将echo
命令的输出写入两个文件:

该ls
命令显示tee
成功创建的文件example1.txt
和example2.txt
.
隐藏输出
如何使用Linux tee命令?要告诉tee
将命令输出存储在文件中并跳过终端输出,请使用以下语法:
[command] | tee [options] [filename] >/dev/null
在下面的示例中,tee
创建一个包含网络接口数据的文件,跳过标准输出:

将一个命令的输出重定向到另一个
Linux如何使用tee命令?tee
不必是管道中的最后一个命令。使用它将输出转发到另一个命令:
[command] | tee [options] [filename] | [command]
在以下示例中,tee
将ls
命令的输出存储到example.txt
并将该文件的内容传递给grep 命令,该命令查找并显示单词“example”的所有实例:

忽略中断
要tee
即使在上一个命令被中断后也能正确退出,请添加参数-i
(或--ignore-interrupts
):
[command] | tee -i [filename]
下一个示例显示了tee
从ping 命令写入输出并成功完成操作,即使在ping
被中断后Ctrl+C
:

将 tee 与 Sudo 一起使用
Linux tee命令用法示例:为了能够tee
写出属于其他用户的超级用户拥有的文件或文件,将sudo命令的权利之前tee
。
[command] | sudo tee [options] [filename]
下面的示例显示了写入根拥有的sudoex.txt
. 当sudo
添加的命令,则操作完成:

在 Vim 编辑器中使用 tee
如何使用Linux tee命令?如果你在Vim 中打开和编辑一个 root 拥有的文件而不使用该sudo
命令,尝试保存更改会产生一个错误:

要覆盖此错误,请在 Vim 中键入以下内容:
:w !sudo tee %

输入sudo
密码后,Vim 显示警告但将更改写入文件。
注意:要在 Vim 中正确管理文件,尤其是在执行更改时,你需要知道如何在 Vim 中保存文件并退出以及如何在 Vim 中撤消和重做更改。
诊断写入非管道的错误
Linux如何使用tee命令?要指示tee
在进程失败时打印错误消息,请使用-p
参数:
[command] | tee -p [filename]
的默认操作tee -p
是在检测到写入管道的错误时立即退出并打印错误消息。要更改写入错误时命令的行为,请使用--output-error
参数,后跟指定行为的模式:
[command] | tee --output-error=[mode] [filename]
有四种可能的模式:
warn
– 诊断写入任何输出的错误。warn-nopipe
– 诊断写入任何非管道输出的错误。exit
– 在写入任何输出时出错退出。exit-nopipe
– 写入任何非管道输出出错时退出。
在 Bash 脚本中使用 tee 命令
该tee
命令经常出现在 bash 脚本中。考虑以下示例:

上面的脚本打印“Hello World”消息并将输出存储在日志文件中。执行脚本会在tmp
文件夹中创建一个日志文件。日志包含脚本的输出:

查看日志文件
Linux tee命令用法示例:将脚本输出写入日志文件通常由>
操作员执行:
./testbash.sh > testbash.log
上面的命令会创建一个日志文件,但不会向标准输出写入任何内容。
使用tee
创建日志文件,并看到在终端的输出:
./testbash.sh | tee testbash.log
查看帮助和版本信息
Linux如何使用tee命令:tee
通过键入以下命令查看命令的当前版本:
tee --version
有关tee
命令语法和可用参数的说明,请使用命令的帮助参数:
tee --help
结论
如何使用Linux tee命令?通过阅读本教程,你了解了如何tee
在管道中使用命令来管理命令输出。文章还谈到了tee
在 bash 脚本中的使用。
在此Linux 命令备忘单中阅读有关 shell 命令的更多信息。