I/O redirection
standard output
root@aliyun:~# cat foo
bar # 标准输出流默认绑定的是显示器
root@aliyun:~# cat foo > output.txt #把标准输出流重定向到 output.txt 这个文件,不在屏幕上显示。
root@aliyun:~# cat output.txt
bar
standard error
root@aliyun:~# cat nonexist.txt > output.txt
cat: nonexist.txt: No such file or directory # nonexist.txt 这个文件不存在。这是标准错误信息。默认绑定的也是显示器。
file descriptor
In Unix and related computer operating systems, a file descriptor (FD, less frequently fildes) is an abstract indicator (handle) used to access a file or other input/output resource, such as a pipe or network socket.
简单来说 file descriptor 可以来访问 I/O 资源。就是一个数字。把每一个资源视为一个房间的话,那么 file descriptor 就是代表这个资源的房间号。拿着房间号就可以访问这个房间的资源。
standard Input stream
Standard input is a stream from which a program
reads
its input data.
The program requests data transfers by use of the read operation.
Not all
programs require stream input.
For example, the dir and ls programs (which display file names contained in a directory) may take command-line arguments, but perform their operations without any stream data input.
Unless redirected
, standard input is inherited from the parent process. In the case of aninteractive shell
, that is usually associated with thekeyboard
.
不重定向,交互式的 Shell,标准输入流和键盘
关联。标准输入流的这个 file descriptor(房间号) 是0
。
standard output stream
Standard output is a stream to which a program
writes
its output data.
The program requests data transfer with the write operation.
Not all
programs generate output.
For example, the file rename command (variously called mv, move, or ren) is silent on success.
Unless redirected
, standard output is inherited from the parent process. In the case of aninteractive shell
, that is usually thetext terminal
which initiated the program.
不重定向,交互式 Shell, 标准输出流和终端关联。标准输出流的这个 file descriptor(房间号) 是1
。
standard error stream
Standard error is another
output stream
typically used by programs to output error messages or diagnostics. It is a streamindependent
of standard output and can beredirected separately
.
标准错误流的这个 file descriptor(房间号) 是2
。
重定向的语法
[FILE_DESCRIPTOR]>
注意 file_descriptor
和 >
要连着写。
输出流重定向
root@aliyun:~# cat foo 1> output.txt #1
root@aliyun:~# cat foo > output.txt #2
# 可知 > 是 1> 简写形式。
错误流重定向
root@aliyun:~# cat nonexist.txt 2> output.txt
2>&1
use
&1
toreference
the value of thefile descriptor 1 (stdout)
.
&1
表示引用标准输出流(fd = 1)
的值。
root@aliyun:~# cat foo > output.txt 2>&1
# 意思就是将标准错误流(fd = 2)重定向到和标准输出流(fd = 1)相同的位置(output.txt)。
root@aliyun:~#
References
1.理解 shell script idiom redirect
2. everything is a file descriptor
3. standard streams 标准流
4. I/O 重定向
5. software clobbering
6. file descriptor