If several redirections are used together, does changing their order make difference?
How shall one understand the meaning of their order? Is the chained channel of redirections built as reading the redirections from left to right, or from right to left?
For example
command 2>&1 > somefile command > somefile 2>&1
Thanks and regards!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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>&1directs both standard output and standard error to the file dirlist, while the command
ls 2>&1 > dirlistdirects 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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0