exec 3 <&1做什么?


14

我知道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.

据此,我了解<输入流,>输出流。那怎么exec 3<&1办?

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


@Gnouc显然是正确的,但是应该注意的是,后者exec 3<&1不同于3<&1后者会影响单个命令,而前者会影响当前的shell。
mikeserv

Answers:


14

来自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.

我做了一些调试strace

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

对于3<&1

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

对于3>&1

dup2(1, 3)                              = 3

对于2>&1

dup2(1, 2)                              = 2

似乎3<&13>&1将stdout复制到文件描述符3 完全相同。


从手册页中,我希望它会引发重定向错误,因为stdout尚未打开以供输入。但是,它确实确实重复了标准输入(&0)。怎么样?
Orion

2
@orion:内部,同一dup2()syscall用于任何类型的文件描述符;bash的x>&yvs x<&y只是语法糖。而且,当标准输入输出连接到一个tty,tty设备常常是通过打开读+写和0只复制到1和2
user1686

@grawity exec 3<&1一样exec >&3吗?
真凯2014年

否,但与相同exec 3>&1
2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.