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.

I have been trying to figure out the relationship between file descriptors. One thing I don't understand is, how is:

ls -l /bin/usr > ls-output.txt 2>&1

different from:

ls -l /bin/usr 2>&1 >ls-output.txt
share|improve this question
    
I know it doesnt work..what I am confused about is why..ultimately the stderr is pointing to the stdout. –  Scrooj Mar 25 '13 at 3:45

2 Answers 2

up vote 5 down vote accepted

The order of the redirection is important as they are executed sequentially:

>filename 2>&1

stdout (fd 1) will point to filename and afterwards the stderr (fd 2) will point to the the target of stdout in this example filename.

That means that both stdout and stderr get redirected to filename

2>&1 >filename

Here stderr (fd 2) will point to the target of stdout and afterwards stdout (fd 1) will redirect to filename.

This means that stderr will redirect to the original target of stdout and stdout gets redirected to filename.

So in short the order of redirects is important as each filedescriptor is independent of each other.

Additional Information

For further information have a look at some other questions and answers such as:

share|improve this answer
    
Thanks for the precise explanation –  Scrooj Mar 25 '13 at 3:52

They're not.

a>&b redirects fd a to fd b. if a is not given, 1 is assumed. 1 is stdout and 2 is stderr.

Some shells (e.g. Bash) also let you specify &> file to redirect both at the same time. However, > 2>&1 is more portable.

share|improve this answer
1  
Aaron,thanks for the reply..I think they are different,the first outputs the stderr to the file but the second outputs the stderr to the stdout(screen)..But i dont get how this happens..both are ultimately pointing to stdout –  Scrooj Mar 25 '13 at 3:40

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.