Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I wonder why the standard errors are always output first despite the redirection order in my commands:

"first > then 2>&1"

lyg@lyg-VirtualBox:~$ > txt
lyg@lyg-VirtualBox:~$ ls txt  tt ttt > txt  2>&1
lyg@lyg-VirtualBox:~$ cat txt
ls: cannot access tt: No such file or directory
ls: cannot access ttt: No such file or directory
txt

"first 2> then 1>&2"

lyg@lyg-VirtualBox:~$ ls txt  tt ttt 2> txt  1>&2
lyg@lyg-VirtualBox:~$ cat txt
ls: cannot access tt: No such file or directory
ls: cannot access ttt: No such file or directory
txt

What is the detailed procedure of redirection for each?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Because ls stats all the files first, outputs error messages for the missing files, then it sorts the existing filenames and outputs them.

So the redirections have no impact on the order of the output. You can test this by writing a simple command that outputs something to both fds, and their order will be the same

$ f() { echo stdout; echo stderr >&2; }
$ f > /tmp/output 2>&1
$ cat /tmp/output
stdout
stderr
$ f 2> /tmp/output >&2
$ cat /tmp/output
stdout
stderr
share|improve this answer

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.