Shell redirection i/o order

后端 未结 4 732
青春惊慌失措
青春惊慌失措 2020-11-28 08:32

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

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

and

l         


        
4条回答
  •  萌比男神i
    2020-11-28 09:02

    The Bash manual has a clear example (similar to yours) to show that the order matters and also explains the difference. Here's the relevant part excerpted (emphasis mine):

    Note that the order of redirections is significant. For example, the command

    ls > dirlist 2>&1

    directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist, while the command

    ls 2>&1 > dirlist

    directs only the standard output to file dirlist, because the standard error was made a copy of the standard output before the standard output was redirected to dirlist.

    This post explains it from the POSIX viewpoint.

    Confusions happen due to a key difference. > redirects not by making left operand (stderr) point to right operand (stdout) but by making a copy of the right operand and assigning it to the left. Conceptually, assignment by copy and not by reference.

    So reading from left-to-right which is how this is interpreted by Bash: ls > dirlist 2>&1 means redirect stdout to the file dirlist, followed by redirection of stderr to whatever stdout is currently (which is already the file dirlist). However, ls 2>&1 > dirlist would redirect stderr to whatever stdout is currently (which is the screen/terminal) and then redirect stdout to dirlist.

提交回复
热议问题