Bash redirection explanation
Intuitively, there are 3 concepts in file descriptor in bash: file descriptor number, file descriptor, and the file.
File descriptor numbers are 0
, 1
, 2
, ..., which usually refers to a file descriptor or nothing.
A file descriptor is an object issued by operating system to access a file.
A file is a piece of data, can be a file on a hard disk, a TCP stream, a UDP stream, ...
File can be seen as a warehouse which contains goods ( data), A warehouse can be attached with many (or zero) gate ( file descriptor). The gate is issued (making, destroying) by the manager ( OS). Each gate has a key ( file descriptor number) in order to use/open the door to access good (data) from/to the warehouse. A key can be used to access at most one gate.
With this understanding, this command command 2>&1
should be interpreted as following. And you will recognize that there is nothing to do with redirection.
2>&1
is a file descriptor duplication operation. Read more about all other operations here.&1
refer the file descriptor denoted by file descriptor number1
.- Duplicate this file descriptor and assign it to the file descriptor number
2
.
With the warehouse, gate, key metaphor: 2>&1
means
- Find the key number
1
- Find the gate associated with this key
- Duplicate this gate. In other words, issues the manager to create another gate which can be used to access the the same warehouse as the gate in the previous step.
- Assign number
2
to the key associated with the new gate
Another example
N<&M-
: duplicate the file descriptor denoted by file descriptor number M
, assign to file descriptor number N
, then destroy the old descriptor.
Or this can be interpreted as move the file descriptor denoted by file descriptor number M
to the file descriptor number N
.