Shell redirection i/o order

后端 未结 4 740
青春惊慌失措
青春惊慌失措 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条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 09:04

    Redirections are:

    • processed from left to right.
    • interpreted iteratively:
      • an earlier redirection can affect a later one:
        • if an earlier redirection has redirected a given stream (identified by a file descriptor number, such as 1 for stdout (the default), and 2 for stderr), later redirections targeting that stream refer to the already-redirected version.
      • but not vice versa - a later redirection has no retroactive effect on the the target of an earlier redirection:
        • e.g., if you specify file descriptor 1 as the target in an earlier redirection, what 1 means at that time is locked in, even if 1 is redirected later.
    • Note, however, that output isn't actually sent until all redirections are in place, and that any redirection-target output files are created or truncated before command execution begins (this is the reason why you can't read from and redirect output to the same file with a single command).

    Applied to the example from the question:

    • >file 2>&1:

      • >file first redirects stdout (file descriptor 1, implied by not prefixing > with a file descriptor number) to output file file
      • 2>&1 then redirects stderr (2) to the already redirected stdout (1).
      • The net effect is that both original streams end up in file.
    • 2>&1 >file:

      • 2>&1 first redirects stderr to the then-original stdout; since file descriptor 2 participates in no further redirections, stderr output will therefore go to whatever stdout was defined as at that point - i.e., the original stdout, given that this is the first redirection.
        • Technically, the original stdout file descriptor is duplicated, and that duplicate is what stderr then refers to, which explains why it isn't affected by a later redirection of stdout.
      • >file then redirects the original stdout to file - but that has no effect anymore on the already locked-in redirection of stderr.
      • The net effect is that only sent-directly-to-stdout output is captured in file, while sent-to-stderr output is output to (the original, unredirected) stdout.

提交回复
热议问题