Bash – Duplication of file descriptors in redirection

bashfile-descriptorsio-redirectionshell

From https://www.gnu.org/software/bash/manual/html_node/Redirections.html

Bash handles several filenames specially when they are used in redirections, as described
in the following table:

/dev/fd/fd If fd is a valid integer, file descriptor fd is
duplicated.

/dev/stdin File descriptor 0 is duplicated.

/dev/stdout File descriptor 1 is duplicated.

/dev/stderr File descriptor 2 is duplicated.

what does "duplicated" mean here? Can you give some examples?

Best Answer

Redirections are implemented via the dup family of system functions. dup is short for duplication and when you do e.g.:

3>&2

you duplicate (dup2 ) filedescritor 2 onto filedescriptor 3, possibly closing filedescriptor 3 if it's already open (which won't do a thing to your parent process, because this happens in a forked off child (if it does not (redirections on shell functions in certain contexts), the shell will make it look as if it did)).

When you do:

1<someFile

it'll open someFile on a new file descriptor (that's what the open syscall normally does) and then it'll dup2 that filedescriptor onto 1.

What the manual says is that if one of the special dev files listed takes the place of someFile, the shell will skip the open-on-a-new-fd step and instead go directly to dup2ing the matching filedescriptor (i.e., 1 for /dev/stdout, etc.) onto the target (filedescriptor on the left side of the redirection).