exec 3<&1 有什么作用?

Zhe*_*kai 15 shell bash io-redirection file-descriptors exec

我知道exec可以在当前 shell 上进行 I/O 重定向,但我只看到如下用法:

exec 6<&0   # Link file descriptor #6 with stdin.
            # Saves stdin.

exec 6>&1   # Link file descriptor #6 with stdout.
            # Saves stdout.
Run Code Online (Sandbox Code Playgroud)

据我了解,这<是用于输入流,>用于输出流。那么有什么作用exec 3<&1呢?

PS:我从Bats 源代码中找到了这个

cuo*_*glm 15

来自bash manpage

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 evalu?
       ates 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 re?
       direction 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)

我做了一些调试strace

sudo strace -f -s 200 -e trace=dup2 bash redirect.sh
Run Code Online (Sandbox Code Playgroud)

对于3<&1

dup2(3, 255)                            = 255
dup2(1, 3)                              = 3
Run Code Online (Sandbox Code Playgroud)

对于3>&1

dup2(1, 3)                              = 3
Run Code Online (Sandbox Code Playgroud)

对于2>&1

dup2(1, 2)                              = 2
Run Code Online (Sandbox Code Playgroud)

似乎与3<&1完全相同3>&1,将标准输出复制到文件描述符 3。

  • @orion:在内部,任何类型的文件描述符都使用相同的 `dup2()` 系统调用;bash 的 `x&gt;&amp;y` 与 `x&lt;&amp;y` 只是语法糖。此外,当 stdio 连接到 tty 时,tty 设备经常打开以进行读写,并且只是从 0 复制到 1 和 2。 (2认同)