使用 Windows Batch 脚本在 FOR 循环中计数
谁能解释一下吗?我可以使用 Windows 命令提示符进行循环计数,使用此方法:
SET /A XCOUNT=0
:loop
SET /A XCOUNT+=1
echo %XCOUNT%
IF "%XCOUNT%" == "4" (
GOTO end
) ELSE (
GOTO loop
)
:end
但此方法不起作用(它为文件中的每一行打印出“1”)。它的行为就像变量超出范围:
SET /A COUNT=1
FOR /F "tokens=*" %%A IN (config.properties) DO (
SET /A COUNT+=1
ECHO %COUNT%
)
Can anyone explain this? I am able to count in a loop using the Windows command prompt, using this method:
SET /A XCOUNT=0
:loop
SET /A XCOUNT+=1
echo %XCOUNT%
IF "%XCOUNT%" == "4" (
GOTO end
) ELSE (
GOTO loop
)
:end
But this method does not work (it prints out "1" for each line in the file). It acts like the variable is out of scope:
SET /A COUNT=1
FOR /F "tokens=*" %%A IN (config.properties) DO (
SET /A COUNT+=1
ECHO %COUNT%
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不起作用,因为整个
for
循环(从for
到最后的右括号,包括之间的命令those) 会在遇到时、在开始执行之前进行评估。换句话说,在运行循环之前,
%count%
被替换为其值1
。您需要的是这样的:
使用
!
而不是%
的延迟扩展将为您提供预期的行为。另请参阅此处。另请记住,
setlocal/endlocal
实际上限制了内部更改的范围,以便它们不会泄漏。如果您想在endlocal
之后使用count
,则必须使用因您所遇到的问题而成为可能的“技巧”:假设内部范围内的
count
已变为 7。因为整个命令在执行之前被解释,所以它实际上变成:然后,当它被执行时,内部作用域被关闭,将
count
返回到它的原始值。但是,由于将count
设置为 7 发生在外部作用域中,因此它实际上泄漏了您需要的信息。您可以将多个子命令串在一起以泄漏您需要的尽可能多的信息:
It's not working because the entire
for
loop (from thefor
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.In other words,
%count%
is replaced with its value1
before running the loop.What you need is something like:
Delayed expansion using
!
instead of%
will give you the expected behaviour. See also here.Also keep in mind that
setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to usecount
after theendlocal
, you have to use a "trick" made possible by the very problem you're having:Let's say
count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:Then, when it's executed, the inner scope is closed off, returning
count
to it's original value. But, since the setting ofcount
to seven happens in the outer scope, it's effectively leaking the information you need.You can string together multiple sub-commands to leak as much information as you need:
for a = 1 到 100 步骤 1
Windows 中的命令行。如果在批处理文件中运行,请使用 %%a。
for a = 1 to 100 step 1
Command line in Windows . Please use %%a if running in Batch file.
这是生成所有 10.xxx 地址的批处理文件
Here is a batch file that generates all 10.x.x.x addresses