2>&1 redirect in Bourne shell takes the output sent to a file descriptor 2 (by default, standard error) and sends it instead to file descriptor 1 (by default a standard output).
But what does 2<&1 redirect do?
Does it send stderr to stdin?
My theory was that it was sending stdin to stderr (e.g. same as 1>&2) but experimentally, that is NOT the case:
$ perl -e 'print "OUT\n"; print STDERR "ERR\n"; \
while (<>) { print "IN WAS $_\n";}' \
> out3 2<&1
df
$ cat out3
ERR
OUT
IN WAS df
Note that standard out AND standard error both went to file out3 where stdout was redirected.
The
<&operator duplicates an “input” file descriptor. According to IEEE Std 1003.1-2001 (aka Single Unix Specification v3, the successor to POSIX), it’s supposed to be an error to say2<&1if 1 is not a file descriptor open for input. However, it appears thatbashis lazy and doesn’t care if the file descriptor is open for input or for output.So both
2<&1and2>&1simply perform the system calldup2(1, 2), which copies file descriptor 1 to file descriptor 2.You can check by running a command like this, since redirections are performed left-to-right:
Then in another window, run
lsofon thesleepprocess. You’ll see that both file descriptors 1 and 2 point to/dev/null. Example (on my Mac):