在这个bash命令1>& 2中​​,&符号表示什么

时间:2010-02-26 10:56:02

标签: bash scripting

快速的一个,2>&1将stderr重定向到stdout,但是&符号是什么意思?我知道如果我们将2 > 1输出到名为1的文件,那么&符号会做什么?

6 个答案:

答案 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文件指针。这就是文件描述符相互覆盖的原因。

根据Linux man page

  

[重复文件描述符]指的是相同的打开文件描述   因此共享文件偏移和文件状态标志;例如,如果   通过在其中一个描述符上使用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 operators2>&1运算符或&>运算符在重定向之前或之后将进程的流绑定在一起。