Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmd 2>&1 > log vs cmd > log 2>&1 [duplicate]

What is the difference between:

cmd > log 2>&1 

and

cmd 2>&1 > log 

where cmd is a command?

Which should I prefer and why?

like image 392
dogbane Avatar asked Jan 15 '11 13:01

dogbane


People also ask

Can I run 2 cmd?

Try using the conditional execution & or the && between each command either with a copy and paste into the cmd.exe window or in a batch file. Additionally, you can use the double pipe || symbols instead to only run the next command if the previous command failed.

What is cmd used for?

It can be used to execute entered commands and perform advanced administrative functions. It can also be used to troubleshoot and solve certain kinds of Windows issues.

Can you pipe in cmd?

Pipe shell command The | command is called a pipe. It is used to pipe, or transfer, the standard output from the command on its left into the standard input of the command on its right. # First, echo "Hello World" will send Hello World to the standard output.


1 Answers

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.

like image 99
John Kugelman Avatar answered Sep 24 '22 08:09

John Kugelman