读取 stdin,同时写入文件和 stdout。管道中”一分为二”,既保存日志又继续传递数据。

语法

command | tee [OPTIONS] file1 [file2 ...]

核心选项

选项说明
(无)覆盖写文件,stdout 输出
-a追加写文件(append),不覆盖
-i忽略 SIGINT 信号(Ctrl+C)

常用场景

1. 命令输出同时保存到文件

make build 2>&1 | tee build.log

终端实时看输出,同时写入 build.log。

2. 追加模式(不覆盖已有内容)

./script.sh | tee -a run.log

3. 同时写入多个文件

echo "hello" | tee file1.txt file2.txt file3.txt

4. 管道中间保存快照,继续传递

cat data.txt | tee snapshot.txt | grep "error" | wc -l

snapshot.txt 保存完整数据,grep 继续处理。

5. 需要 sudo 写文件时

普通重定向 > 在 sudo 场景下会失败,tee 可以解决:

# 错误方式(sudo 只作用于 echo,重定向由 shell 执行,权限不够)
sudo echo "config" > /etc/app.conf
 
# 正确方式
echo "config" | sudo tee /etc/app.conf
 
# 追加
echo "config" | sudo tee -a /etc/app.conf

6. 只写文件,不输出到终端

command | tee output.log > /dev/null

7. 同时捕获 stdout 和 stderr

command 2>&1 | tee all.log

8. 用 process substitution 分流到不同文件

command | tee >(grep "ERROR" > errors.log) >(grep "WARN" > warnings.log) > /dev/null

与重定向的对比

方式终端看到输出写文件
cmd > file否是
cmd | tee file是是
cmd | tee file > /dev/null否是

记忆口诀

tee = T 型管道分叉,一路给终端,一路给文件