预备知识

存取文件离不开被称为"文件描述符"的特殊数字。

  • 0 — stdin(标准输入)
  • 1 — stdout (标准输出)
  • 2 — stderr (标准错误)

操作符

  • 只读模式:<
  • 截断写入模式:>
  • 追加写入模式:>>

实战演练

  • >:清空文件原有内容,重新添加,>>:不清空文件原有内容,追加内容
[root@shaofeng ~]# echo '>' > temp.txt
[root@shaofeng ~]# cat temp.txt
>
[root@shaofeng ~]# echo '>>' >> temp.txt
[root@shaofeng ~]# cat temp.txt
>
>>
  • cmd 1>1.txt 2>2.txt
cmd 2>&1 out.txt
  • 将错误输出内容,从控制台转到文件
➜  ~ git:(master) ✗ touch a1
➜  ~ git:(master) ✗ chmod 000 a1
➜  ~ git:(master) ✗ cat a1
cat: a1: Permission denied
➜  ~ git:(master) ✗ cat a1 2> err.txt
➜  ~ git:(master) ✗ cat err.txt
cat: a1: Permission denied
  • tee filename:将标准输出内容,重定向到某个文件(filename = -:则到控制台)
[root@shaofeng ~]# echo who is this | tee out.txt
who is this
[root@shaofeng ~]# cat out.txt
who is this
  • -a:tee中的-a选项,用于追加内容
[root@shaofeng ~]# echo who is this | tee -a out.txt
who is this
[root@shaofeng ~]# cat out.txt
who is this
who is this
  • cat -n:将从stdin中接收到的每一行数据前加上行号并写入stdout
[root@shaofeng ~]# echo who is this | tee - | cat -n
     1  who is this
     2  who is this

工作原理

  • 将文件重定向到命令
  • 将脚本内部文本重定向

  • 自定义文件描述符

    • 创建文件描述符用于读取
    [root@shaofeng ~]# exec 3<out.txt
    [root@shaofeng ~]# cat <&3
    Who is this
    
    • 创建文件描述符用于写入(截断模式)
    [root@shaofeng ~]# exec 4>out.txt
    [root@shaofeng ~]# echo Who is this >&4
    [root@shaofeng ~]# cat out.txt
    Who is this
    
    • 创建文件描述符用于写入(追加模式)
    [root@shaofeng ~]# exec 5>>out.txt
    [root@shaofeng ~]# echo who is this >&5
    [root@shaofeng ~]# cat out.txt
    Who is this
    who is this
    

results matching ""

    No results matching ""