cmd.exe 重定向操作符顺序和位置 [英] cmd.exe redirection operators order and position

查看:24
本文介绍了cmd.exe 重定向操作符顺序和位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先说订单

以下工作将 stdoutstrerr 重定向到 nul.

The following works to redirect stdout and strerr to nul.

command 1>nul 2>&1

以下没有

command 2>&1 1>nul

为什么顺序很重要?如何用人类可以理解的语言来阅读这些表达?

Why does the order matter? How could these expression be read in a human understandable language?

关于职位

这行得通

command 1>nul 2>&1

还有这个

1>nul 2>&1 command

为什么?任何有关语法规则的官方参考文档都会有所帮助.

Why? Any official reference documentation on syntax rules would be helpful.

推荐答案

command 2>&1 1>nul 不工作 不正确.有用.但像往常一样,它会做你问的而不是你想要的

command 2>&1 1>nul doesn't work is not correct. It works. But as usual, it does what you asked not what you wanted

从左到右:

  • 2>&1 到流 2 (stderr) 的数据将被发送到流 1 (stdout) 所在的句柄的copy/duplicate使用.

  • 2>&1 data to stream 2 (stderr) will be sent to a copy/duplicate of the handle that stream 1 (stdout) is using.

1>nul 数据流 1 将被发送到 nul.

1>nul data to stream 1 will be sent to nul.

重复是关键.数据不会发送到任何流 1 点,而是发送到流句柄的副本.当流 1 被重定向时,流 2 有自己的句柄,即前一个流 1 的副本.更改流 1 不会影响流 2

The duplicate is the key. Data is not sent to whatever stream 1 points, but to a copy of the stream handle. When stream 1 is redirected, stream 2 has its own handle, a copy of the previous stream 1. Changing stream 1 does not affect stream 2

现在,让我们看看工作代码,从左到右

Now, lets see the working code, from left to right

  • 1>nul 设置流1中的句柄指向nul

  • 1>nul Set the handle in stream 1 to point to nul

2>&1 将流2中的句柄设置为流1中使用的句柄的副本,即nul的句柄

2>&1 Set the handle in stream 2 to a copy of the handle in use in stream 1, that is, a handle to nul

关于职位

大多数情况下,位置(命令前、命令后或两者)都无关紧要.要执行命令,解析器必须首先准备命令将使用的流.在开始执行命令之前,如果认为有必要(尝试重定向 rem 命令输入或输出),则会完成此准备工作.

Most of the time the position (before command, after command or both) is irrelevant. To execute a command, the parser has to first prepare the streams that the command will use. This preparation is done if it is considered necessary (try redirecting rem command input or output) before starting command execution.

唯一不同的情况是我们想要从命令中获取的内容和解析器理解的内容不同.一个明显的例子是当我们需要输出一个带有结尾数字的字符串时.代码为

The only cases where there is a difference are when what we want to obtain from the command and what the parser understands are not the same. One obvious case is when we need to output a string with an ending digit. Code as

echo 1 2 3>file 

不会将完整字符串发送到目标文件.1 2 将回显到控制台,写入流 3 的数据(此命令中没有内容)将发送到 file

will not send the full string to the target file. 1 2 will be echoed to console, and the data written to stream 3 (nothing in this command) will be sent to file

当然,可以在数据的末尾(3> 之间)添加一个空格,但是这个空格将包含在输出中.如果这不可接受,解决方案是将重定向放在命令的开头

Of course, a space can be added at the end of the data (between 3 and >), but this space will be included in the output. If this is not acceptable, the solution is to place the redirection at the start of the command

>file echo 1 2 3

这篇关于cmd.exe 重定向操作符顺序和位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆