ls > file, 会将标准输出重定向到文件file
ls 1>&file, 将标准输出的文件描述符置为file的一个拷贝,这样的結果也导致ls的結果输出到文件file中
但是,执行ls 2>&file,时提示bash: file: ambiguous redirect. 而文件file中什么也没有。标准错误的文件描述符为什么不能置为文件file的描述符的一个拷贝?而标准输出就可以?
I/O重定向中提制标准错误的一个疑問
-
- 帖子: 64
- 注册时间: 2009-07-02 19:11
- lexdene
- 帖子: 434
- 注册时间: 2010-02-21 16:19
- 来自: 大连
- 联系:
Re: I/O重定向中提制标准错误的一个疑問
好高深的问题啊!
帮你顶一下。
帮你顶一下。
大连Linux User Group: http://groups.google.com/group/dalian-lug?hl=zh-CN
- icyomik
- 帖子: 76
- 注册时间: 2010-10-30 17:52
Re: I/O重定向中提制标准错误的一个疑問
我看了一下,也是想不明白,ls 0>&file也是错误,或者和文件描述符的相关定义冲突了吧,反正不明白为什么ls 1>&file可以。
- lexdene
- 帖子: 434
- 注册时间: 2010-02-21 16:19
- 来自: 大连
- 联系:
Re: I/O重定向中提制标准错误的一个疑問
我到处搜了很久,也没有搜到相关的资料。
大连Linux User Group: http://groups.google.com/group/dalian-lug?hl=zh-CN
- astolia
- 论坛版主
- 帖子: 6703
- 注册时间: 2008-09-18 13:11
Re: I/O重定向中提制标准错误的一个疑問
man bash的REDIRECTION一节里,有如下描述
至于为什么1>&file能起效,我觉得是因为bash把1>&file和>&file做了等价处理,而>&file在man中的描述如下
结果也证明了1>&file等价于>file 2>&1
如果需要直接的证据请自行阅读bash源代码
我从中没有看到任何word可以是文件名的描述,只说了word可以是1~2位数字或者是-。所以你用文件名当word应该是不正确的用法。Duplicating File Descriptors
The redirection operator
[n]<&word
is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of
that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to
-, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.
The operator
[n]>&word
is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits
in word do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and word does not
expand to one or more digits, the standard output and standard error are redirected as described previously.
至于为什么1>&file能起效,我觉得是因为bash把1>&file和>&file做了等价处理,而>&file在man中的描述如下
我写了个非常简单的程序进行验证Redirecting Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file
whose name is the expansion of word.
There are two formats for redirecting standard output and standard error:
&>word
and
>&word
Of the two forms, the first is preferred. This is semantically equivalent to
>word 2>&1
代码: 全选
$ cat a.c
#include <stdio.h>
int main() {
printf("xxx");
while(1);
return 0;
}
$ gcc a.c
$ ./a.out 1>&file &
[1] 12417
$ ls -l /proc/12417/fd/*
lrwx------ 1 xxx xxx 64 2011-06-13 22:02 /proc/12417/fd/0 -> /dev/pts/0
l-wx------ 1 xxx xxx 64 2011-06-13 22:02 /proc/12417/fd/1 -> /home/xxx/file
l-wx------ 1 xxx xxx 64 2011-06-13 22:02 /proc/12417/fd/2 -> /home/xxx/file
如果需要直接的证据请自行阅读bash源代码
- lexdene
- 帖子: 434
- 注册时间: 2010-02-21 16:19
- 来自: 大连
- 联系:
Re: I/O重定向中提制标准错误的一个疑問
楼上NB啊!
大连Linux User Group: http://groups.google.com/group/dalian-lug?hl=zh-CN