使用这个程序(cs.exe
):
class Program
{
static void Main(string[] args)
{
foreach (var item in args)
{
Console.WriteLine(item);
}
}
}
然后运行:
> cs.exe go\to\a_path
go\to\a_path
> cs.exe "go\to\a path"
go\to\a path
> cs.exe "go\to\a path\"
go\to\a path"
> cs.exe 'go\to\a path\'
'go\to\a
path\'
这意味着如果你的路径有一个空格所以你引用它,请非常小心不要在末尾放置尾随 \
,否则你的程序
可能只是无法处理它,因为它在末尾错误地包含了一个 "
。单引号甚至更奇怪!
PowerShell 表现出类似的行为,但没有单引号和双引号之间的区别。
我如何理解这种行为?在 cmd 中评估反斜杠的基本规则是什么,以便可以一致地解释这一点?
最佳答案
由于您不是调用内部 cmd
命令,而是调用可执行文件,因此此行为不是由 cmd
引起的,而是由命令行参数解析器例程引起的。在 Windows 中,程序不接收参数的集合/数组/集,而是一个包含所有参数的字符串,每个程序对该字符串进行标记以获取每个元素。这通常由编译器包含的例程完成,编译器隐藏此操作并向代码公开处理参数的更简单方法。
C Command-Line argument parser 的文档指出
Arguments are delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. Note that the caret (
^
) is not recognized as an escape character or delimiter.A double quotation mark preceded by a backslash,
\"
, is interpreted as a literal double quotation mark ("
).Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
If an even number of backslashes is followed by a double quotation mark, then one backslash (
\
) is placed in the argv array for every pair of backslashes (\\
), and the double quotation mark ("
) is interpreted as a string delimiter.If an odd number of backslashes is followed by a double quotation mark, then one backslash (
\
) is placed in the argv array for every pair of backslashes (\\
) and the double quotation mark is interpreted as an escape sequence by the remaining backslash, causing a literal double quotation mark ("
) to be placed in argv.
还有一组未记录/非官方规则 ( How Command Line Parameters Are Parsed )
- Outside a double quoted block a
"
starts a double quoted block.- Inside a double quoted block a
"
followed by a different character (not another"
) ends the double quoted block.- Inside a double quoted block a
"
followed immediately by another"
(i.e.""
) causes a single"
to be added to the output, and the double quoted block continues.
.Net
参数解析rules只是这些规则的推导。如果您需要不同的行为,那么您应该使用 Environment.CommandLine
属性来检索完整的命令行字符串并编写您自己的解析代码。
关于windows - 为什么尾随反斜杠后跟引号在 cmd 中表现如此奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41607045/