且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Windows批处理脚本在FOR循环中计数

更新时间:2022-04-13 03:28:59

它不工作,因为 c>循环(从到$ c>到最后右括号,包括之间的命令)正在被评估, 开始执行。

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

换句话说,%count%

你需要的是:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

使用而不是延迟扩展将提供预期的行为。另请参见此处

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.

还要记住, setlocal / endlocal 实际上限制了内部改变的范围,不漏出。如果您想在 endlocal 之后使用 count ,您必须使用 你可能遇到的问题:

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 use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

让我们说 count 已在内部范围内变为7。因为整个命令在执行之前被解释,它有效地变成:

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

然后,当执行 关闭,返回 count 为它的原始值。但是,由于 count 到七的设置发生在外部范围,它有效地泄漏你需要的信息。

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count 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:

endlocal && set count=%count% && set something_else=%something_else%