Bash的输入输出重定向
出自Linux Wiki
使用Bash可以方便的用<和>实现输出输入的重定向,本文讨论重定向的一些细节和技巧。
基础知识
文件描述符(File Descriptor),用一个数字(通常为0-9)来表示一个文件。常用的文件描述符如下:
文件描述符 | 名称 | 常用缩写 | 默认值 |
0 | 标准输入 | stdin | 键盘 |
1 | 标准输出 | stdout | 屏幕 |
2 | 标准错误输出 | stderr | 屏幕 |
我们在简单地用<或>时,相当于使用 0< 或 1>(下面会详细介绍)。
管道“|”(pipe line),把上一个命令的 stdout 接到下一个命令的 stdin;
tee 命令的作用是在不影响原本 I/O 的情况下,将 stdout 复制一份到档案去;
简单重定向
- cmd > file
- 把cmd命令的输出重定向到文件file中。如果file已经存在,则清空原有文件,使用bash的noclobber选项可以防止覆盖原有文件。
- cmd >> file
- 把cmd命令的输出重定向到文件file中,如果file已经存在,则把信息加在原有文件后面。
- cmd < file
- 使cmd命令从file读入
- cmd << text
- 从命令行读取输入,直到一个与text相同的行结束。除非使用引号把输入括起来,此模式将对输入内容进行shell变量替换。如果使用 <<- ,则会忽略接下来输入行首的tab,结束行也可以是一堆tab再加上一个与text相同的内容,可以参考后面的例子。
- cmd <<< word
Supply text of word, with trailing newline, as input to cmd. (This is known as a here string, from the free version of the rc shell.)
cmd <> file
Open file for reading and writing on the standard input. The contents are not destroyed.*
cmd >| file
Send output of cmd to file (overwrite), even if the shell’s noclobber option is set.
k、 exec 命令:常用来替代当前 shell 并重新启动一个 shell,换句话说,并没有启动子 shell。使用这一命令时任何现有环境都将会被清除。exec 在对文件描述符进行操作的时候,也只有在这时,exec 不会覆盖你当前的 shell 环境。