Tee命令在Linux中是读取标准输入并把结果同时写入标准输出和的一个或多个文件。基本在终端上显示命令输出,同时把输出重定向到文件,比如用户可用tee命令在root用户文件中添加一个新行。
tee命令基本语法:
[command] | tee [options] [filename]
tee基本是用来显示命令标准输出并保存于文件,比如我们执行‘hostnamectl命令来打印系统主机名及其他详细信息,再把标准输出存为‘host_info.txt’:
$ hostnamectl | tee host_info.txt
Static hostname: ywnz
Icon name: computer-laptop
Chassis: laptop
Machine ID: 7a138ee71db94e8785d1a4dbe54dde7e
Boot ID: 34d27941b74941a9a29bc424f66613bc
Operating System: openSUSE Leap 15.2
CPE OS Name: cpe:/o:opensuse:leap:15.2
Kernel: Linux 5.3.18-lp152.75-default
Architecture: x86-64
可以在cat命令中查看文件‘host_info.txt’的内容:
$ cat host_info.txt
如果是想把输出写入多个文件,可添加一个由空格分隔的文件列表为参数:
$ command | tee file1 file2…fileN
默认情况下每次运行tee命令就会覆盖文件内容,如果要输出为附加内容,需要使用a或append:
$ command | tee -a file
想允许tee命令在执行中断时正常退出:
$ command | tee -i file
隐藏输出:
$ command | tee file >/dev/null
tee命令允许您写入由root用户或其他人拥有的文件。例如,如果您想在下面的文件中添加一个新行,您将收到“权限被拒绝(permission denied)”错误,因为sudo不执行输出的重定向:
$ sudo echo "add a newline" > /etc/sudoers
bash: /etc/sudoers: Permission denied
可以用tee:
$ echo "add a newline" | sudo tee -a /etc/sudoers
shell中使用tee:
$ vi /tmp/testbash.sh
#!/bin/bash
LOGFILE=/tmp/test-logs-$(date +%d%m%Y)
echo "Append the logs routinely" | tee -a $LOGFILE