windows Windows批处理文件中的“for”循环中的随机变量不会改变
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6500217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random variable not changing in "for" loop in windows batch file
提问by mike
I'm trying to print out a Random number multiple times but in the for loop I use, it doesn't reset the variable. Here's my code.
我试图多次打印出一个随机数,但在我使用的 for 循环中,它不会重置变量。这是我的代码。
@echo off
for %%i in (*.txt) do (
set checker=%Random%
echo %checker%
echo %%i% >> backupF
)
echo Complete
There are 5 text files and so I want it to print 5 different random numbers but it just prints the same random number 5 times. Any help would be greatly appreciated. Thanks!
有 5 个文本文件,所以我希望它打印 5 个不同的随机数,但它只打印 5 次相同的随机数。任何帮助将不胜感激。谢谢!
回答by Andriy M
I'm not sure how you've been able to have it print even one random number. In your case, %checker%
should evaluate to an empty string, unless you run your script more than once from the same cmd
session.
我不确定你是如何让它打印一个随机数的。在您的情况下,%checker%
应评估为空字符串,除非您在同一cmd
会话中多次运行脚本。
Basically, the reason your script doesn't work as intended is because the variables in the loop body are parsed and evaluated before the loop executes. When the body executes, the vars have already been evaluated and the same values are used in all iterations.
基本上,您的脚本没有按预期工作的原因是循环体中的变量在循环执行之前被解析和评估。当主体执行时,变量已经被评估并且在所有迭代中使用相同的值。
What you need, therefore, is a delayed evaluation, otherwise called delayed expansion. You need first to enable it, then use a special syntax for it.
因此,您需要的是延迟评估,也称为延迟扩展。您需要首先启用它,然后对其使用特殊语法。
Here's your script modified so as to use the delayed expansion:
这是您修改后的脚本以使用延迟扩展:
@echo off
setlocal EnableDelayedExpansion
for %%i in (*.txt) do (
set checker=!Random!
echo !checker!
echo %%i% >> backupF
)
endlocal
echo Complete
As you can see, setlocal EnableDelayedExpansion
enables special processing for the delayed expansion syntax, which is !
s around the variable names instead of %
s.
如您所见,setlocal EnableDelayedExpansion
为延迟扩展语法启用特殊处理,即!
围绕变量名称使用%
s而不是s。
You can still use immediate expansion (using %
) where it can work correctly (basically, outside the bracketed command blocks).
您仍然可以使用立即扩展(使用%
),它可以正常工作(基本上,在括号中的命令块之外)。
回答by Stefan
on my system I have to write
在我的系统上我必须写
set checker=Random
instead of
代替
set checker=!Random!