Linux tee 的使用小结

Linux tee 命令用于读取标准输入的数据,并将其内容输出成文件。

tee 指令会从标准输入设备读取数据,将其内容输出到标准输出设备,同时保存成文件。

我们多用来进行日志的保存。用下面的 test.sh 可执行文件来进行演示。

[root@localhost ~]# cat test.sh
#! /usr/bin/bash

echo "hello world"
for i in {1..3}
do
        echo $i
done
[root@localhost ~]#
  1. tee。执行 testh.sh 并对它执行过程中的输出进行保存。2>&1 :表示标准输出和错误输出。
  2. [root@localhost ~]# ./test.sh 2>&1 | tee log
    hello world
    1
    2
    3
    [root@localhost ~]# cat log
    hello world
    1
    2
    3
    [root@localhost ~]#
  3. tee -a。追加内容到原文件内容的后面。
  4. [root@localhost ~]# ./test.sh 2>&1 | tee -a log
    hello world
    1
    2
    3
    [root@localhost ~]# cat log
    hello world
    1
    2
    3
    hello world
    1
    2
    3
    [root@localhost ~]#
  5. tee。清空原文件内容,重新写入。
  6. [root@localhost ~]# ./test.sh 2>&1 | tee log
    hello world
    1
    2
    3
    [root@localhost ~]# cat log
    hello world
    1
    2
    3
    [root@localhost ~]#
  7. 当 test.sh 文件有语法错误时。如下:done --> donw
  8. [root@localhost ~]# cat test.sh
    #! /usr/bin/bash
    # test.sh
    echo "hello world"
    for i in {1..3}
    do
            echo $i
    donw                    # 正确的应该是 done
    [root@localhost ~]#
  9. tee。
  10. [root@localhost ~]# ./test.sh 2>&1 | tee log
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    [root@localhost ~]# cat log
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    [root@localhost ~]#
  11. tee -a。
  12. [root@localhost ~]# ./test.sh 2>&1 | tee -a log
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    [root@localhost ~]# cat log
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    [root@localhost ~]#
  13. tee。

  14. [root@localhost ~]# ./test.sh 2>&1 | tee log
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    [root@localhost ~]# cat log
    hello world
    ./test.sh: line 8: syntax error: unexpected end of file
    [root@localhost ~]#

注意:在某些场景下,比如:我不想保存对的信息(hello world),只想保存错误的信息(./test.sh: line 8: syntax error: unexpected end of file),怎么办呢?

[root@localhost ~]# ./test.sh 2>> | tee log                      # -bash: syntax error near unexpected token `|'

[root@localhost ~]# ./test.sh "2>>" | tee log                      # 这个没有报错,但是不符合期望,因为保存的是正确的信息,而不是错误的。(单双引号 结果一样)

[root@localhost ~]# ./test.sh 2>&2 | tee log                      # 这个没有报错,但是不符合期望,因为保存的是正确的信息,而不是错误的。

暂时还知道怎样单独保存错误的信息。

猜你喜欢

转载自blog.csdn.net/tk1023/article/details/108885946
tee
今日推荐