cmd 文件中的 % 和 %% 有什么区别? [英] What is the difference between % and %% in a cmd file?
问题描述
我最近在 .cmd 文件中包含了与此类似的一行:
I recently included a line similar to this in a .cmd file:
for /f %%f in ('dir /b .directory*.sql') DO sqlcmd -b -o ".directoryoutput\%%f.txt" -i ".directory\%%f"
最初我只使用了 %f,它在命令行上运行时可以正常工作,但在通过文件运行时却无法正常工作.当我切换到 %%f 时,它在文件中工作.只是想知道有什么区别.
Originally I had only used %f, and it would work fine when run on the command line, but not when run through the file. When I switched to %%f, it worked in the file. Just wondering what the difference is.
推荐答案
(更详细的解释可以在 存档的 Microsoft KB 文章.)
要知道的三件事:
- 百分号在批处理文件中用于表示命令行参数:
%1
、%2
、... 中间有任何字符的两个百分号被解释为一个变量:
- The percent sign is used in batch files to represent command line parameters:
%1
,%2
, ... Two percent signs with any characters in between them are interpreted as a variable:
echo %myvar%
<小时>
这是为什么?
Why's that?
例如,如果我们执行您的(简化的)命令行
For example, if we execute your (simplified) command line
FOR /f %f in ('dir /b .') DO somecommand %f
在批处理文件中,规则 2 会尝试解释
in a batch file, rule 2 would try to interpret
%f in ('dir /b .') DO somecommand %
作为变量.为了防止这种情况发生,您必须应用规则 3 并使用第二个 %
对 %
进行转义:
as a variable. In order to prevent that, you have to apply rule 3 and escape the %
with an second %
:
FOR /f %%f in ('dir /b .') DO somecommand %%f
这篇关于cmd 文件中的 % 和 %% 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!