Bash: 重定向文件描述符

Bash: Redirecting file descriptors

我希望有人能解释一个现象。正如标题所示,我正在学习文件描述符的重定向。一路上我遇到了一个关于重定向符号使用的问题,特别是在设置永久重定向时。我注意到在某些情况下,使用 < 还是 > 似乎并不重要。例如,使用以下脚本:

#!/bin/bash

#Setting file descriptor 3 to redirect  to STDIN
exec 3<&0

#Setting STDIN to read from input file
exec 0<inputFile


while read var
do
    echo "$var"

done

#Setting STDIN to read from file descriptor 3 which is redirected to the default STDIN
exec 0<&3

read -p "Enter a word:" word

echo "$word"

令我惊讶的是,在语句 exec 3<&0exec 0<&3 中使用 >< 似乎并不重要。在这些陈述中的任何一个中,似乎如果我换掉重定向符号,我仍然会得到完全相同的结果。对我来说,对行进行相同类型的更改似乎很明显:

exec 0<inputFile

对比

exec 0>inputFile

不会产生相同的结果,因为将 STDIN 重定向到文件与将文件重定向到 STDIN 不同。

所以我的问题是:

  1. < 对比 >:

    # Why aren't there any differences between these two statements?
    exec 3<&0
    exec 3>&0
    
  2. 3<&0 对比 0<&3:

    # Why is there a difference between these two statements?
    exec 3<&0
    exec 0<&3
    

这种类型的重定向对我来说已经足够困难了,我可以在没有这些类型的不一致的情况下绕过头并保持直线。任何解释将不胜感激。

复制文件描述符时,没关系,dup2被调用,无论你使用<还是> .

关闭 文件描述符时也会发生同样的情况。您可以使用 n>&-n<&-.


However why then is 0<&3 not the same thing as 3<&0?

我链接的 dup2 规范中对此进行了解释:

int dup2(int fildes, int fildes2);

The dup2() function shall fail if:

[EBADF]

The fildes argument is not a valid open file descriptor or the argument fildes2 is negative or greater than or equal to {OPEN_MAX}.

exec 0<&3 的情况下,Bash 调用 dup2(3,0) 并且确实收到 EBADF 错误(因为我们在 fildes[ 的情况下=39=]=3 这在当时不是一个有效的打开文件描述符)。您可以使用 strace:

轻松检查
$ strace -e dup2 bash -c 'exec 0>&3'
dup2(3, 0)                              = -1 EBADF (Bad file descriptor)
bash: 3: Bad file descriptor
dup2(10, 0)                             = 0
+++ exited with 1 +++