Skip to content

tee 命令:读取标准输入并写入文件和标准输出

1. 命令简介

tee 命令会同时将其输入写入到标准输出和一个或多个文件中。这个命令的名字来源于工程中的 T 型管道,它将一个输入流分成两个或更多输出流。tee 命令在需要同时查看输出结果和保存结果到文件时特别有用。

2. 基本语法

bash
tee [选项] [文件...]

3. 常用选项

  • -a:追加到文件而不是覆盖
  • -i:忽略中断信号(SIGINT)
  • -p:诊断写入错误

4. 基础使用示例

  1. 将输出同时写入文件和显示在屏幕上:

    bash
    echo "Hello, World!" | tee file.txt
  2. 追加到文件:

    bash
    echo "Appended line" | tee -a file.txt
  3. 将输出写入多个文件:

    bash
    echo "Multiple files" | tee file1.txt file2.txt
  4. 在管道中使用 tee:

    bash
    ls -l | tee file.txt | grep "\.txt"

5. 进阶使用技巧

  1. 使用 tee 记录命令执行过程:

    bash
    make 2>&1 | tee build.log
  2. 将输出同时写入文件和另一个命令:

    bash
    echo "Test" | tee >(wc -c) >/dev/null
  3. 使用 tee 创建文件的副本:

    bash
    cat original.txt | tee copy1.txt copy2.txt > /dev/null
  4. 在 sudo 操作中使用 tee:

    bash
    echo "New line" | sudo tee -a /etc/some_config_file

6. 实用示例

  1. 在安装过程中保存日志:

    bash
    sudo apt-get update | tee update.log
  2. 在文件开头插入文本:

    bash
    echo "New first line" | cat - file.txt | tee file.txt
  3. 将命令输出同时发送到文件和另一个程序:

    bash
    ping google.com | tee ping.log | grep "time="
  4. 在脚本中使用 tee 记录日志:

    bash
    #!/bin/bash
    {
        echo "Starting script at $(date)"
        # 脚本命令
        echo "Ending script at $(date)"
    } | tee -a script.log

7. 注意事项

  • 使用 tee 时要注意文件权限,特别是在写入系统文件时。
  • 当使用 tee 覆盖文件时,要小心不要丢失重要数据。
  • 在管道中使用 tee 可能会影响管道的退出状态。

8. 相关命令

  • cat:连接文件并打印到标准输出
  • script:记录终端会话
  • logger:向系统日志发送日志消息
  • ts:给每行输出添加时间戳

9. 技巧与建议

  1. 使用 tee 检查 sudo 命令的输出:

    bash
    echo "test" | sudo tee /root/test.txt | cat -
  2. 在重定向时使用 tee 来查看输出:

    bash
    command | tee >(cat 1>&2) > output.txt
  3. 结合 mktemp 创建临时日志文件:

    bash
    log=$(mktemp)
    command | tee "$log"
  4. 使用 tee 在多个终端会话中共享输出:

    bash
    command | tee >(nc -l 12345) | tee output.txt
    # 在另一个终端:nc localhost 12345

tee 命令虽然看似简单,但在日常系统管理和脚本编写中非常有用。它允许你同时查看命令输出并将其保存到文件中,这在调试、日志记录和数据处理中特别有价值。熟练使用 tee 可以帮助你更有效地管理命令输出,提高工作效率。