Whats the difference between redirections “1>/dev/null 2>&1” and “ 2>&1 1>/dev/null”?

无人久伴 提交于 2021-02-04 21:37:04

问题


Whats the difference between redirections 1>/dev/null 2>&1 and 2>&1 1>/dev/null

It seems 1st one displays output to stdout but not the second one.

Can somebody explain ! Thanks


回答1:


Expanding on Lokendra26's answer a bit: /dev/null is a special file on your system, a device for discarding anything written to it. It's common to send output there if you don't want to see it. "File" in this case, and unix terminology in general, can be both a normal disk file, or a device like the null device or your terminal.

The "1" and "2" are file descriptors, designators for places to send output. Programs use FD 1, "standard output", as the target for ordinary output, and FD 2, "standard error", for error output. These file descriptors can point to different files at different times. Normally they both point at your terminal, so you se output from your programs written there.

The & operator is more than just for disambiguation. It actually means "look up whatever this FD points to at this point".

It is important to understand these details in order to understand the difference between the two redirections you are asking about.

1>/dev/null 2>&1 this is actually two statements, processed in sequence. First, point "standard output" at the null device (thus discarding anything written to it). Second, point "standard error" at whatever "standard output" is pointing to, in this case /dev/null. The end result is that output from both file descriptors will be discarded.

2>&1 1>/dev/null is likewise two statements. First, point "standard error" at whatever "standard output" is pointing to. Normally this will be your terminal, as I wrote above. Second, point "standard output" at /dev/null. End result - only "standard output" is discarded, "standard error" will still print to your terminal.




回答2:


In Unix ">" stands for the redirection of the output to a file or elsewhere.

"1>" - Stands for output from stdout pipeline

"2>" - Stands for output from stderr (error) pipeline (Errors goes into this pipeline)

So from your question,

"1>/dev/null" : Tell the system to direct standard output to null(file) kept at /dev

"2>&1" : Tell the system to redirect the output of stderr pipeline to the place where the output of stdout pipeline is going. So In this case you get both the stdout and the stderr output written inside a single file.

While "2>&1 1>" this doesn't make sense to me as it would be equivalent to "2>&1"

PS. If you are confused about the &1 part then that is used to resolve the ambiguity which may occur when 1 is the name of a file.

Hope that makes sense to you.



来源:https://stackoverflow.com/questions/35314283/whats-the-difference-between-redirections-1-dev-null-21-and-21-1-dev-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!