What does "2>&1" do when posted BEFORE 1>x?
A further example might be helpful: let's redirect fd1 to a file, redirect fd2 to fd1, then redirect fd1 to a different file:
$ ( echo "this is stdout"; echo "this is stderr" >&2 ) 1>foo 2>&1 1>bar
$ cat foo
this is stderr
$ cat bar
this is stdout
We can see that 2>&1
sends stderr to the "foo" file that stdout was redirected to, but when we redirect stdout to "bar" we don't alter stderr's destination.
Similarly, 2>&1 1>/dev/null
redirects stderr to whatever stdout is pointing to (see /proc/$$/fd
), and when stdout is discarded, stderr is not altered (still visible).
This is the technique used to capture a command's error output, ignoring the regular output:
error_output=$( some_command 2>&1 1>/dev/null )
From man bash
:
"Note that the order of redirections is significant. For example, the command
ls > dirlist 2>&1
directs both standard output and standard error to the file dirlist, while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist."