Bash: file descriptor redirection

I hope someone can explain the phenomenon. Because the header indicates that I will learn about file descriptor redirection. Along the way, I came across a question related to the use of the redirection symbol, especially when setting up a constant redirection. I noticed that in some cases it doesn't matter if I use <or >. For example, working with the following script:

#!/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"

To my surprise, it doesn’t matter if I use >either <in exec 3<&0or operators exec 0<&3. In any of these statements, it seems that if I replace the redirection characters, I still get the same result. It seems obvious to me that making the same types of changes to a string:

exec 0<inputFile

against.

exec 0>inputFile

, STDIN - , STDIN.

, :

  • < vs >:

    # Why aren't there any differences between these two statements?
    exec 3<&0
    exec 3>&0
    
  • 3<&0 vs 0<&3:

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

, . .

+4
1

, dup2, , < >.

. n>&- n<&-.


0<&3 , 3<&0?

dup2, :

int dup2(int fildes, int fildes2);

dup2() , :

[EBADF]

fildes fildes2 {OPEN_MAX}.

exec 0<&3, Bash dup2(3,0) EBADF ( fildes = 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 +++
+5

Source: https://habr.com/ru/post/1665330/


All Articles