问题描述
我最近在 windows cmd 中运行了一个带有单引号的命令,发现它的行为与我预期的不一样.
I recently ran a command in windows cmd with single quotes in it and found that it did not behave as I expected.
从尝试使用谷歌搜索windows 批处理单引号与双引号"我发现了几篇文章,其中人们询问让 windows 像双引号一样对待单引号,以及 bash 如何以不同的方式对待单引号和双引号.但是,我无法轻松找到对 Windows 批处理命令中单引号的作用的明确解释.
From trying to google "windows batch single quote vs double quote" I've found a few articles where people asked about having windows treat single quotes like double quotes, and about how bash treats single quotes and double quotes differently. However, I couldn't easily find an explicit explanation of what single quotes do in windows batch commands.
那么单引号在 Windows 批处理文件中的作用是什么?他们是否执行任何形式的引用功能?
So what do single quotes do in windows batch files? Do they perform any sort of quoting functionality at all?
推荐答案
cmd.exe 命令处理器根本不使用单引号,除非将要在 FOR/F 语句中运行的命令括起来:
Single quotes are not used at all by the cmd.exe command processor except to enclose the command to run within a FOR /F statement:
for /f %%A in ('someCommand') do ...
或者如果使用了 USEBACKQ 选项,则指定要由 FOR/F 处理的字符串:
Or to specify a string to process by FOR /F if the USEBACKQ option is used:
for /f "usebackq" %%A in ('some string') do ...
cmd.exe 处理的所有其他引用都使用双引号完成.但是,有像 WMIC 这样的 Windows 实用程序(外部命令)使用单引号来实现自己的引用目的.但是没有标准 - 每个实用程序都可以自由地对单引号进行解释.
All other quoting handled by cmd.exe is done with double quotes. However, there are Windows utilities (external commands) like WMIC that use single quotes for their own quoting purposes. But there is no standard - each utility is free to have its own interpretation of single quotes.
cmd.exe 与各种命令行实用程序使用的不一致的转义和引用规则通常使发现任何给定情况所需的正确语法成为一项挑战.
The inconsistent escape and quote rules used by cmd.exe vs. various command line utilities often makes it a challenge to discover the correct syntax needed for any given situation.
这里有一些关于在 cmd.exe 中使用双引号 "
的重要注意事项.
Here are some important notes about using double quotes "
with cmd.exe.
双引号是一个简单的状态机.第一个
"
打开引用,下一个关闭引用.
Double quotes are a simple state machine. The first
"
turns quoting on, the next turns it off.
所有特殊字符在引用时都被视为文字值,除了 %
和 字符总是,如果启用了延迟扩展,则
!
字符,如果启用了延迟扩展和 !
字符,则 ^
字符也会出现在行内的某处.
All special characters are treated as literal values when quoted, except for the %
and <newLine>
characters always, and the !
character if delayed expansion is enabled, and the ^
character if delayed expansion is enabled and !
also appears somewhere within the line.
如果引用关闭,那么您可以将 "
转义为 ^"
以防止它打开引用.但是一旦引用打开,你就无法逃避结束的 "
.下一个 "
将始终关闭引用.
If quoting is off, then you can escape a "
as ^"
to prevent it from turning quoting on. But once quoting is on, you cannot escape the closing "
. The very next "
will always turn quoting off.
这篇关于Windows 批处理文件中的单引号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!