在Linux/Ubuntu/Debian中使用 tee 命令将输出显示在终端并写入文件中
在日常的 Linux 系统操作中,我们常常需要将命令的输出重定向到文件中以便于后续查看和处理。本文将通过几个常见示例,介绍如何使用 tee 命令来同时将输出显示在终端并写入文件中。
基础命令:ls > file
ls > file 是一个非常基础的命令,它的作用是将 ls 命令的输出重定向到 file 文件中。运行该命令后,你会发现终端中没有任何输出,但 file 文件中会包含 ls 命令的结果。
ls > file
使用 tee 命令
示例 1:ls | tee file
与 ls > file 不同,ls | tee file 命令不仅会将 ls 命令的输出写入 file 文件中,还会在终端中显示该输出。这在需要实时查看输出结果的同时又想保存输出内容时非常有用。
ls | tee file
示例 2:crontab -l | tee crontab-backup.txt | sed ‘s/old/new/’ | crontab -
在这个示例中,我们使用 tee 命令备份 crontab 配置文件并进行内容替换:
crontab -l列出当前的定时任务。tee crontab-backup.txt将列出的内容备份到crontab-backup.txt文件中。sed 's/old/new/'命令替换内容,将所有old字符串替换为new。- 最后,将替换后的内容重新载入到
crontab中。
这个命令的好处在于可以在进行内容替换的同时保留一个备份,以便在出错时可以回退。
crontab -l | tee crontab-backup.txt | sed 's/old/new/' | crontab -
示例 3:ls | tee file1 file2 file3
这个命令展示了 tee 命令可以将输出写入多个文件中。ls 命令的输出会被同时写入 file1、file2 和 file3,并在终端中显示。
ls | tee file1 file2 file3
示例 4:ls | tee –a file
有时我们希望将新的输出追加到已有的文件中,而不是覆盖文件内容。这时可以使用 -a 选项。ls | tee -a file 命令会将 ls 命令的输出追加到 file 文件中,同时在终端中显示输出。
ls | tee -a file
