Bash

exec 3<&1 做什麼?

  • December 1, 2016

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

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

exec 6&gt;&1   # Link file descriptor #6 with stdout.
           # Saves stdout.

據我了解,這&lt;是用於輸入流,&gt;用於輸出流。那麼做exec 3&lt;&1什麼呢?

PS:我是從Bats 原始碼中找到的

來自bash manpage

Duplicating File Descriptors
      The redirection operator

             [n]&lt;&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]&gt;&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.

我做了一些調試strace

sudo strace -f -s 200 -e trace=dup2 bash redirect.sh

對於3&lt;&1

dup2(3, 255)                            = 255
dup2(1, 3)                              = 3

對於3&gt;&1

dup2(1, 3)                              = 3

對於2&gt;&1

dup2(1, 2)                              = 2

似乎與將 stdout 複製到文件描述符 33&lt;&1完全相同。3&gt;&1

引用自:https://unix.stackexchange.com/questions/120532