Linux tee命令详解
tee
是 Linux 中一个常用的命令,用于从标准输入读取数据并同时写入标准输出和文件。它的名字来源于管道中的“T”型接头,形象地表示数据的分流。
基本语法
tee [选项] [文件...]
常用选项
-a
或--append
:将数据追加到文件末尾,而不是覆盖文件。-i
或--ignore-interrupts
:忽略中断信号(如Ctrl+C
)。-p
:诊断写入错误到非管道的情况。--help
:显示帮助信息。--version
:显示版本信息。
使用示例
将输出同时显示在屏幕并保存到文件
echo "Hello, World!" | tee output.txt
这会将
Hello, World!
显示在屏幕上,并同时写入output.txt
文件。将输出追加到文件
echo "Another line" | tee -a output.txt
这会将
Another line
追加到output.txt
文件的末尾,而不是覆盖文件。将输出写入多个文件
echo "Multiple files" | tee file1.txt file2.txt
这会将
Multiple files
写入file1.txt
和file2.txt
两个文件。结合管道使用
ls -l | tee directory_list.txt
这会将
ls -l
的输出显示在屏幕上,并同时保存到directory_list.txt
文件中。忽略中断信号
echo "Ignoring interrupts" | tee -i output.txt
即使按下
Ctrl+C
,tee
也会继续运行。
高级用法
将输出重定向到多个命令
echo "Data" | tee >(grep "Da" > grep_output.txt) >(wc -c > wc_output.txt)
这会将
Data
同时传递给grep
和wc
命令,并将结果分别保存到grep_output.txt
和wc_output.txt
文件中。使用
tee
调试脚本./script.sh | tee script_output.log
这会将
script.sh
的输出同时显示在屏幕上并保存到script_output.log
文件中,便于调试。
总结
tee
命令在需要同时查看和保存命令输出时非常有用,特别是在调试脚本或记录日志时。通过结合管道和重定向,tee
可以实现复杂的数据处理任务。