cmd 2>&1 > log vs cmd > log 2>&1

前端 未结 2 1203
醉梦人生
醉梦人生 2020-12-07 12:14

What is the difference between:

cmd > log 2>&1

and

cmd 2>&1 > log

where cmd is a comm

相关标签:
2条回答
  • cmd > log 2>&1
    

    Redirects STDOUT to log and than replaces STDERR with the redirected STDOUT.

    cmd 2>&1 > log
    

    Replaces STDERR with STDOUT and then redirects the original STDOUT to log.

    0 讨论(0)
  • 2020-12-07 13:02

    Order matters. The way to reason about redirections is to read them from left to right and realize that redirections make streams point at the same place. They don't make streams point at each other.

    What does that mean? If you say 2>&1 then you are redirecting stderr to wherever stdout is currently redirected to. If stdout is going to the console then stderr is, too. If stdout is going to a file then stderr is as well. If you follow this up by then redirecting stdout, stderr still points to what stdout used to point to. It does not "follow" stdout to the new location.

    Right

    cmd > log 2>&1
    

    This redirects stdout to log and then redirects stderr to wherever stdout is now being redirected, which is log.

    End result: both stdout and stderr are redirected to log.

    Wrong

    cmd 2>&1 > log
    

    This redirects stderr to wherever stdout is currently being redirected, which is typically the console. Then stdout is redirected to log. Remember that stderr does not "follow" stdout, so it continues to redirect to the console.

    End result: stdout is redirected to the log file and stderr is (still) sent to the console. This is almost certainly not what you want.

    0 讨论(0)
提交回复
热议问题