Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random variable not changing in "for" loop in windows batch file

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.

@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!

like image 775
mike Avatar asked Jun 27 '11 23:06

mike


1 Answers

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.

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.

You can still use immediate expansion (using %) where it can work correctly (basically, outside the bracketed command blocks).

like image 190
Andriy M Avatar answered Oct 28 '22 21:10

Andriy M