Why is 1>a.txt 2>&1 different from 1>a.txt 2>a.txt ? (Example shown)

shell

EDIT

Please see not only the accepted answer but also the other one(s).

Question

Why does redirecting both STDOUT and STDERR to the same file not work, although it looks like the same as 1>[FILENAME] 2>&1 ?

Here is an example:

perl -e 'print "1\n" ; warn "2\n";' 1>a.txt 2>a.txt
cat a.txt
# outputs '1' only.

Well, why? I thought that this works because… STDOUT is redirected to a.txt and so is STDERR. What happened to STDERR?

Best Answer

Both your redirections truncate the file, so the second (in chronologial order of execution) will overwrite the first. Try

rm a.txt ; touch a.txt ; perl -e 'print "1\n" ; warn "2\n";' 1>>a.txt 2>>a.txt

Or just use the same file descriptor

perl -e 'print "1\n" ; warn "2\n";' 1>a.txt 2>&1