Why does 2>&1 need to come before a | (pipe) but after a “> myfile” (redirect to file)?

前端 未结 3 1876
礼貌的吻别
礼貌的吻别 2021-01-31 05:59

When combining stderr with stdout, why does 2>&1 need to come before a | (pipe) but after a > myfile (redirect to file)?

3条回答
  •  清酒与你
    2021-01-31 06:49

    To add to ormaaj's answer:

    The reason you need to specify redirection operators in the proper order is that they're evaluated from left to right. Consider these command lists:

    # print "hello" on stdout and "world" on stderr
    { echo hello; echo world >&2; }
    
    # Redirect stdout to the file "out"
    # Then redirect stderr to the file "err"
    { echo hello; echo world >&2; } > out 2> err
    
    # Redirect stdout to the file "out"
    # Then redirect stderr to the (already redirected) stdout
    # Result: all output is stored in "out"
    { echo hello; echo world >&2; } > out 2>&1
    
    # Redirect stderr to the current stdout
    # Then redirect stdout to the file "out"
    # Result: "world" is displayed, and "hello" is stored in "out"
    { echo hello; echo world >&2; } 2>&1 > out
    

提交回复
热议问题