快速的一个,2>&1
将stderr重定向到stdout,但是&符号是什么意思?我知道如果我们将2 > 1
输出到名为1
的文件,那么&符号会做什么?
答案 0 :(得分:61)
2>&1
将标准错误(文件句柄2)重定向到标准输出(文件句柄1)当前所在的同一文件。
这也是与位置有关的事情:
prog >x 2>&1 >y
实际上会将标准错误发送到x
,将标准输出发送到y
,如下所示:
x
; x
; y
; 答案 1 :(得分:18)
它将文件描述符1复制到文件描述符2. FD2是stderr而FD1是stdout,因此它使得stderr的任何输出都转到stdout。
答案 2 :(得分:17)
“&”符号属于“1”,因此该片段实际上有三个部分:“2”,“>”,“& 1”。它们分别表示“从输出流2中获取数据(这是标准错误)”,“重定向它”,以及重定向目标,即输出流1.所以“&”这里允许您重定向到现有流,而不是文件。
答案 3 :(得分:15)
format
中的&
重复文件描述符&1
。重复的描述符实际上不像副本,但像旧的别名一样。复制1
允许将多个流重定向到1
而不会互相覆盖。
示例:(没有1
)
&
请注意,$ ls existing-file non-existent-file > tmp 2> tmp
$ cat tmp
existing-file
nt-file: No such file or directory
覆盖了1
写的内容。但不是在我们使用2
:
&
文件描述符是文件(或其他输入/输出资源,如管道或网络套接字)的句柄。当$ ls existing-file non-existent-file > tmp 2>&1
$ cat tmp
ls: non-existent-file: No such file or directory
existing-file
和1
分别重定向到2
时(如第一个示例中所示),它们会独立移动tmp
文件指针。这就是文件描述符相互覆盖的原因。
[重复文件描述符]指的是相同的打开文件描述 因此共享文件偏移和文件状态标志;例如,如果 通过在其中一个描述符上使用lseek(2)来修改文件偏移量, 另一个也改变了偏移量。
请注意,即使tmp
充当别名,&
也意味着将2>&1
重定向到当前指向的2
的流。当1
被重定向到其他内容时,1
指向与2
无关的同一文件。
观察:
1
答案 4 :(得分:7)
来自info bash
:
3.6.7 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.
所以2>&1
将fd 1复制到fd 2上。
答案 5 :(得分:0)
&符号没有做任何事情 - 它是2>&1
运算符中的字符,而不是它本身就是一个东西。
bash支持多个redirection operators,2>&1
运算符或&>
运算符在重定向之前或之后将进程的流绑定在一起。