输出重定向
这个命令执行command1然后将输出的内容存入file,如果file内的已经存在的内容将被新内容替代。如果要将新内容添加在文件末尾,请使用>>操作符。
# 覆盖
command > file
# 追加
command >> file
输入重定向
和输出重定向一样,Unix 命令也可以从文件获取输入,本来需要从键盘获取输入的命令会转移到文件读取内容。语法为:
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
# 覆盖
command 2>file
# 追加
command 2>>file
将 stdout 和 stderr 合并后重定向到 file
# 覆盖
command > file 2>&1
# 追加
command >> file 2>&1
# 或者
# 覆盖
command &> file
# 追加
command &>> file
stdin 和 stdout 都重定向
command < file1 >file2
黑洞:/dev/null 文件
command &> /dev/null
注意: 0 是标准输入(STDIN), 1 是标准输出(STDOUT), 2 是标准错误输出(STDERR)。
这里的 2 和 > 之间不可以有空格,2> 是一体的时候才表示错误输出。
免交互式,从标准输入中读入内容
echo password | passwd --stdin username
tee 重定向的同时在控制台中打印信息
➜ os ll | awk 'NR>1{print $NF}' | tee a.txt
archlinux-2020.09.01-x86_64.iso
cn_windows_7_professional_with_sp1_x64_dvd_u_677031.iso
manjaro-xfce-21.0.4-210506-linux510.iso
ubuntu-20.04.3-live-server-amd64.iso
ubuntu-20.04.3-live-server-amd64.iso
➜ os cat a.txt
archlinux-2020.09.01-x86_64.iso
cn_windows_7_professional_with_sp1_x64_dvd_u_677031.iso
manjaro-xfce-21.0.4-210506-linux510.iso
ubuntu-20.04.3-live-server-amd64.iso
ubuntu-20.04.3-live-server-amd64.iso
参考:
https://www.runoob.com/linux/linux-shell-io-redirections.html