Consider a program hello_and_error
that writes to both stdout and to stderr. To redirect both to stdout:
hello_and_error 2>&1
If you want to redirect both to the same file hello.txt
you can do in bash the following:
hello_and_error &> hello.txt
If you want to do this in a more obvious (but longer) way you should do
hello_and_error 1>hello.txt 2>&1
and not
hello_and_error 2>&1 1>hello.txt
The former is semantically equivalent with hello_and_error &> hello.txt
but looks a bit counter-intuitive to me. The latter seems more natural from the point of view of the user: "first merge stderr in stdout and then redirect this combination to a file", but it only redirects the stdout of hello_and_error
to the file and redirects the stderr of hello_and_error
to the stdout of the shell.
The former is probably more natural from the programmer's point of view. I guess you could compare it to the following pieces of (pseudo-)code.
for redirection 1>hello.txt 2>&1
:
// initialisation to defaults
stdout = 1
stderr = 2
// parse redirection
stdout = file("hello.txt")
stderr = stdout
// result:
// stdout == file("hello.txt")
// stderr == file("hello.txt")
for redirection 2>&1 1>hello.txt
:
// initialisation to defaults
stdout = 1
stderr = 2
// parse redirection
stderr = stdout
stdout = file("hello.txt")
// result:
// stdout == file("hello.txt")
// stderr == 1
A more in depth view on the redirection: http://www.ss64.com/bashsyntax/redirection.html.