Shell redirection i/o order

The Bash manual has a clear example (similar to yours) to show that the order matters and also explains the difference. Here’s the relevant part excerpted (emphasis mine):

Note that the order of redirections is significant. For example, the
command

ls > dirlist 2>&1

directs both standard output (file descriptor 1) and standard error
(file descriptor 2) to the file dirlist, while the command

ls 2>&1 > dirlist

directs only the standard output to file dirlist, because the standard
error was made a copy of the standard output before the standard
output was redirected to dirlist.

This post explains it from the POSIX viewpoint.

Confusions happen due to a key difference. > redirects not by making left operand (stderr) point to right operand (stdout) but by making a copy of the right operand and assigning it to the left. Conceptually, assignment by copy and not by reference.

So reading from left-to-right which is how this is interpreted by Bash: ls > dirlist 2>&1 means redirect stdout to the file dirlist, followed by redirection of stderr to whatever stdout is currently (which is already the file dirlist). However, ls 2>&1 > dirlist would redirect stderr to whatever stdout is currently (which is the screen/terminal) and then redirect stdout to dirlist.

Leave a Comment