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

mik*_*kip 36 bash scripting

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

pax*_*blo 62

2>&1将标准错误(文件句柄2)重定向到标准输出(文件句柄1)当前所在的同一文件.

它也是一个依赖于位置的东西:

prog >x 2>&1 >y
Run Code Online (Sandbox Code Playgroud)

实际上会将标准错误发送到x标准输出,y如下所示:

  • 将标准输出连接到x;
  • 然后将标准误差连接到当前标准输出,即x;
  • 然后将标准输出连接到y;

  • 如果可以的话,我会多次投票.我一直困惑于此,你对*order*重要性的解释比当前的bash文档更清晰:http://www.gnu.org/software/bash/manual/bashref.html#Redirections.谢谢! (3认同)
  • 这总结了一切!在我使用Linux的8年中,没有人这么清楚地解释过这个问题!谢了哥们. (2认同)

Ign*_*ams 18

它将文件描述符1复制到文件描述符2. FD2是stderr而FD1是stdout,所以它使得stderr的任何输出都转到stdout.

  • 谢谢,所以 & 表示输出到文件描述符而不是文件 (2认同)

sle*_*ske 17

&符号属于"1",所以片段实际上有三个部分:"2",">","&1".它们分别表示"从输出流2中获取数据(这是标准错误)","重定向它",以及重定向目标,即输出流1.因此,"&"在此处允许您重定向到现有流而不是文件.


Ros*_*one 17

&&1复制的文件描述符1.重复的描述符实际上不像副本,但像旧的别名一样.复制1允许将多个流重定向到1不相互覆盖.

示例:(否&)

$ ls existing-file non-existent-file > tmp 2> tmp 
$ cat tmp
existing-file
nt-file: No such file or directory
Run Code Online (Sandbox Code Playgroud)

请注意1覆盖2写的内容.但不是在我们使用时&:

$ ls existing-file non-existent-file > tmp 2>&1 
$ cat tmp
ls: non-existent-file: No such file or directory
existing-file
Run Code Online (Sandbox Code Playgroud)

文件描述符是文件(或其他输入/输出资源,例如管道或网络套接字)的句柄.当12被单独重定向到tmp(如第一个示例中)时,它们tmp独立地移动它们的文件指针.这就是文件描述符相互覆盖的原因.

根据Linux手册页:

[重复文件描述符]指的是相同的打开文件描述,因此共享文件偏移和文件状态标志; 例如,如果通过在其中一个描述符上使用lseek(2)修改文件偏移量,则另一个描述符的偏移量也会更改.

请注意,即使&像一个别名行为,2>&1意味着重定向2到该数据流1目前指向.当1重定向到其他内容时,2指向它独立的同一文件1.

注意:

$ ls existing-file non-existent-file > tmp 2>&1 > tmp1
$ cat tmp1
existing-file
$ cat tmp
ls: non-existent-file: No such file or directory
Run Code Online (Sandbox Code Playgroud)


Dou*_*der 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.
Run Code Online (Sandbox Code Playgroud)

所以2>&1将fd 1复制到fd 2上.