Do I understand 2>&1 correctly?

Just curious if this is an accurate explanation of 2>&1:

0,1, and 2 are file descriptors on a Bash shell:

  • 0 = STDIN
  • 1 = STDOUT
  • 2 = STDERR

Typically the shell prints 1 and 2 to the console after a command is run. However, the ">" operator by default only redirects 1 somewhere else.

Therefore, ls / > /tmp/file.txt is essentially the same thing as ls / 1> /tmp/file.txt.

You can explicitly redirect 2 to a file by doing ls / 2>/tmp/file.txt. This changes how the ">" operator works, because now instead of redirecting 1, it now only redirects 2. Therefore, 1 is displayed to console and 2 is redirected to /tmp/file.txt

On the other hand, ls / > /tmp/file.txt 2>&1 essentials first lists / to 1 and prepares that to be redirected to /tmp/file.txt - however it later redirects 2 into the 1 buffer. Finally, when the command completes it write the complete 1 buffer to /tmp/file.txt, which lists both sterr and stout now.

This all said ls / > /tmp/file.txt 2>&1 and ls / 1> tmp/file.txt 2>&1 are essentially the same.

If the above is correct - I don't understand why ls /fileDoesntExist 2> /tmp/file.txt 2>&1 doesn't write an error to the console, since the end calls for 2 to be directed to the 1 buffer and STERROR is being written to a file, so stdout should be printed to the console. The 2>&1 makes the error part of stout. So - shouldn't it write it to the console?

MY BAD - THAT LAST PART DOES WRITE THE ERROR TO THE CONSOLE:

I had a typo on my command (ls /doesntExit 2> /tmp/file.txt 2&>1) my bad.