Understanding file descriptor duplication

Table of Contents

1 Why another web page about this?

I always have a hard time remembering what exactly does:

command > file 2>&1

and:

command 2>&1 > file

The question has been asked and answered a lot:

but never in a way that I really understand.

Therefore, here is MY way of thinking this so that I never have to search the web for it anymore.

2 File descriptors and files

Programs don't see files, they only see integers referring to files (remember a file may be a lot of things in linux).
When a program opens a file for reading for instance, linux adds an entry into a file descriptor table that, well… describes the file. The program is then given the index in the table pointing to the file.

When a program is launched, three files descriptors are opened by default:

  1. the entry number 0 is generally called stdin and points to a read only file associated to the keyboard, bash refers to this file using &0
  2. the entry number 1 is generally called stdout and points to a write only file association to the current terminal, bash refers to this file using &1
  3. the entry number 2 is generally called stderr and points to a write only file association to the current terminal, bash refers to this file using &2

Stdout and stderr are not associated to the same file, but both file are by default associated to the current terminal. I will call them tty1 and tty2 but it is probably a misuse of the words tty. I don't know how it works.
program_start.png

If I open a file, the file descriptor 3 will be used to communicate with this file and bash will allow to refer it as &3.

3 Interpretation of the bash commands

The commands file descriptor manipulation are executed from left to right.
(note: > file is equivalent to 1> file)

3.1 command > file 2>&1

This means:

  1. redirect the content going to file descriptor 1 to the file. The old file is no more pointed to by file descriptor 1
    first_use_case_1.png
  2. then, redirect the content going to the file descriptor 2 to the file pointed by the file descriptor 1
    first_use_case_2.png

Then this commands concatenates the stdout and the stderr contents and put them into file.

3.2 command 2>&1 > file

This means:

  1. redirect the content going to the file descriptor 2 to the file pointed by the file descriptor 1
    second_use_case_1.png
  2. then, redirect the content going to file descriptor 1 to the file. The old file is no more pointed to by file descriptor 1
    second_use_case_2.png

Therefore, this command writes the stderr on the file initially associated to stdout and writes stdout in the file.

Author: Konubinix

Created: 2014-12-22 lun. 17:47

Emacs 24.3.1 (Org mode 8.2.7c)

Validate