Why it is 2>&1 and not 2>>&1 to append to a log file

appendbashredirectionshellstderr

I am redirecting STDOUT and STDERR to a single file, always growing,
so I use always use "append" redirection; this is >>

my command is command >> logfile 2>&1

And it works.

But the STDERR redirection has a single >, which I was using to "create" the file, erasing the previous one, as in command > outlog 2> errlog

Why it does not erase the log file in this case?

Best Answer

When you redirect something to &number, you are not opening a new file at all; you're reusing an already open file along with whatever mode it was opened.

The numbers refer to "open file" handles (file descriptors). So there is no technical difference between how >& and >>& (and indeed <&) would work – they all just mean "clone the existing file descriptor using dup()".

That is, 2>&1 indicates that file descriptor #1 (which you previously opened for appending using >>logfile) is cloned into number #2. And yes, 2<&1 works identically.

Side technical note: Appending vs truncating is not an explicit action done by the shell; it's actually a mode the shell specifies when opening the file, and the rest is performed by the OS itself. For example, when you use > the shell doesn't manually erase the old contents, it just adds O_TRUNC when calling open(). Therefore, when open() isn't called at all, the previous mode remains unchanged.

Related Question