Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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!

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

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.

share|improve this answer
add comment
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.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.