Search code examples
bashshellstdoutstderrio-redirection

Shell redirection i/o order


I'm playing with i/o shell redirection. The commands I've tried (in bash):

ls -al *.xyz 2>&1 1> files.lst

and

ls -al *.xyz 1> files.lst 2>&1

There is no any *.xyz file in current folder.

These commands gives me the different results. The first command shows an error message ls: *.xyz: No such file or directory on the screen. But the second one prints this error message to the file. Why did the first command failed to write an err output to the file?


Solution

  • This error:

    ls: *.xyz: No such file or directory
    

    is being written on stderr by ls binary.

    However in this command:

    ls -al *.xyz 2>&1 1> files.lst
    

    You're first redirecting stderr to stdout which by default goes to tty (terminal)

    And then you're redirecting stdout to a file files.lst, however remember that stderr doesn't redirected to file since you have stderr to stdout redirection before stdout to file redirection. Your stderr still gets written to tty in this case.

    However in 2nd case you change the order of redirections (first stdout to file and then stderr to stdout) and that rightly redirects stderr to a file which is also being used by stdout.