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                      # 这个没有报错,但是不符合期望,因为保存的是正确的信息,而不是错误的。

 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值