understand a sequence of redirections
Yes, the order makes a difference, and they should be read left to right.
command 2>&1 >somefile
means to redirect stderr (2) to the current destination of stdout (the terminal). Then change stdout to go to somefile
. So stderr goes to the terminal, and stdout goes to a file.
command >somefile 2>&1
means to redirect stdout to somefile
, and then to redirect stderr to the same destination as stdout (the file). So both stderr and stdout go to somefile
.
This is explained in section 3.6 of the Bash manual: Redirections.
man bash
says:
REDIRECTION Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redi‐ rection may also be used to open and close files for the current shell execution environment. The following redirection opera‐ tors may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.
and
Note that the order of redirections is significant. For example, the command
ls > dirlist 2>&1
directs both standard output and standard error to the file dirlist, while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist.