输出重定向

这个命令执行command1然后将输出的内容存入file,如果file内的已经存在的内容将被新内容替代。如果要将新内容添加在文件末尾,请使用>>操作符。

  1. # 覆盖
  2. command > file
  3. # 追加
  4. command >> file

输入重定向

和输出重定向一样,Unix 命令也可以从文件获取输入,本来需要从键盘获取输入的命令会转移到文件读取内容。语法为:

  1. command < file

重定向进阶

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:

  • 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
  • 标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
  • 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

默认情况下,command > file 将 stdout 重定向到 file,command < file 将stdin 重定向到 file。

将 stderr 重定向到 file

  1. # 覆盖
  2. command 2>file
  3. # 追加
  4. command 2>>file

将 stdout 和 stderr 合并后重定向到 file

  1. # 覆盖
  2. command > file 2>&1
  3. # 追加
  4. command >> file 2>&1
  5. # 或者
  6. # 覆盖
  7. command &> file
  8. # 追加
  9. command &>> file

stdin 和 stdout 都重定向

  1. command < file1 >file2

黑洞:/dev/null 文件

  1. command &> /dev/null

注意: 0 是标准输入(STDIN), 1 是标准输出(STDOUT), 2 是标准错误输出(STDERR)。

这里的 2 和 > 之间不可以有空格,2> 是一体的时候才表示错误输出。

免交互式,从标准输入中读入内容

  1. echo password | passwd --stdin username

tee 重定向的同时在控制台中打印信息

  1. os ll | awk 'NR>1{print $NF}' | tee a.txt
  2. archlinux-2020.09.01-x86_64.iso
  3. cn_windows_7_professional_with_sp1_x64_dvd_u_677031.iso
  4. manjaro-xfce-21.0.4-210506-linux510.iso
  5. ubuntu-20.04.3-live-server-amd64.iso
  6. ubuntu-20.04.3-live-server-amd64.iso
  7. os cat a.txt
  8. archlinux-2020.09.01-x86_64.iso
  9. cn_windows_7_professional_with_sp1_x64_dvd_u_677031.iso
  10. manjaro-xfce-21.0.4-210506-linux510.iso
  11. ubuntu-20.04.3-live-server-amd64.iso
  12. ubuntu-20.04.3-live-server-amd64.iso

参考:
https://www.runoob.com/linux/linux-shell-io-redirections.html