& 在输出重定向中究竟是什么意思?

AJJ*_*AJJ 20 command-line redirect io

我看到类似command 1> out或 with2>&1来重定向 stderr 的东西,但有时我也看到&>自己,等等。

最好的理解&方式是什么?它究竟意味着什么?

Geo*_*sen 27

&2>&1只是说该号码1是一个文件描述符,而不是文件名。在这种情况下,standard output file descriptor.

如果您使用2>1,那么这会将错误重定向到一个名为的文件,1但如果您使用2>&1,那么它会将其发送到standard output stream.

&>表示同时发送,standard outputstandard error,某处。例如,ls <non-existent_file> &> out.file。让我用一个例子来说明这一点。

设置:

  1. 创建一个koko包含以下内容的文件:

    #!bin/bash
    
    ls j1
    echo "koko2"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使其可执行: chmod u+x koko

  3. 现在注意j1不存在

  4. 现在运行 ./koko &> output

  5. 运行cat output,你会看到

    ls: cannot access 'j1': No such file or directory
    koko2
    
    Run Code Online (Sandbox Code Playgroud)

两者,standard errorls: cannot access 'j1': No such file or directory)和standard outputkoko2),被发送到文件output

现在再次运行它,但这次像这样:

./koko > output
Run Code Online (Sandbox Code Playgroud)

cat output,你只会看到koko2类似的。但不是ls j1命令的错误输出。这将被发送到standard error您将在终端中看到的。

感谢@Byte Commander 的重要说明:

请注意,command >file 2>&1重定向的顺序很重要。如果你改写command 2>&1 >file(这通常不是你想要的),它会首先将命令重定向stdout到文件,然后将命令重定向stderr到它现在未使用的stdout,所以它会显示在终端中,你可以通过管道或重定向它再次,但不会写入文件。

  • `&amp;&gt;`是什么意思? (2认同)
  • “这将被发送到你将在终端中看到的‘标准输出’。” 这不应该是“标准错误”吗? (2认同)

J. *_*nes 6

> FILE 2>&1并且&> FILE是等价的。见8.2.3.2。错误的重定向中的Bash的指南入门第8章

  • IIRC `&amp;&gt; FILE` 仅特定于 Bash 而 `&gt;FILE 2&gt;&amp;1` 可以被更多的 shell 理解。 (3认同)