安卓系统

Linux tee命令示例

10.2 文件打包及压缩实战 -Linux云主机管理运维

10.2 文件打包及压缩实战 -Linux云主机管理运维

目录:

Anonim

tee 命令从标准输入中读取并同时写入标准输出和一个或多个文件。 tee 通常与通过管道的其他命令结合使用。

在本教程中,我们将介绍使用 tee 命令的基础知识。

tee 命令语法

tee 命令的语法如下:

tee

  • OPTIONS
    • -a (-- --append )-不要覆盖文件,而是附加到给定文件。 -i (--ignore --ignore-interrupts )-忽略中断信号。使用 tee --help 查看所有可用选项。
    FILE_NAMES 一个或多个文件。 每个输出数据都被写入。

如何使用 tee 命令

tee 命令最基本的用法是显示程序的标准输出( stdout )并将其写入文件中。

在以下示例中,我们使用 df 命令获取有关文件系统上可用磁盘空间量的信息。 输出通过管道传递到 tee 命令,该命令将输出显示到终端,并将相同的信息写入文件 disk_usage.txt

df -h | tee disk_usage.txt

Filesystem Size Used Avail Use% Mounted on dev 7.8G 0 7.8G 0% /dev run 7.9G 1.8M 7.9G 1% /run /dev/nvme0n1p3 212G 159G 43G 79% / tmpfs 7.9G 357M 7.5G 5% /dev/shm tmpfs 7.9G 0 7.9G 0% /sys/fs/cgroup tmpfs 7.9G 15M 7.9G 1% /tmp /dev/nvme0n1p1 511M 107M 405M 21% /boot /dev/sda1 459G 165G 271G 38% /data tmpfs 1.6G 16K 1.6G 1% /run/user/120

您可以使用cat命令查看 disk_usage.txt 文件的内容。

写入多个文件

tee 命令还可以写入多个文件。 为此,请指定以空格分隔的文件列表作为参数:

command | tee file1.out file2.out file3.out

附加到文件

默认情况下, tee 命令将覆盖指定的文件。 使用 -a (-- --append )选项将输出附加到文件:

command | tee -a file.out

忽略中断

要忽略中断,请使用-i ( –ignore-interrupts ) option. This is useful when stopping the command during execution with ) option. This is useful when stopping the command during execution with CTRL + C ) option. This is useful when stopping the command during execution with and want tee`正常退出时很有用。

command | tee -i file.out

隐藏输出

command | tee file.out >/dev/null

将tee与sudo结合使用

假设您想以sudo用户身份写入root拥有的文件。 以下命令将失败,因为sudo不执行输出的重定向。 重定向以非特权用户身份执行。

sudo echo "newline" > /etc/file.conf

输出将如下所示:

bash: /etc/file.conf: Permission denied

只需在 tee 命令之前添加 sudo ,如下所示:

echo "newline" | sudo tee -a /etc/file.conf

tee 将接收echo命令的输出,提升为sudo权限并写入文件。

结合使用 tee sudo 可以写入其他用户拥有的文件。

结论

tee 命令从标准输入读取并将其写入标准输出和一个或多个文件。

如果您有任何问题或反馈,请随时发表评论。

三通终端