13

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!

1
  • The script above doesnt make sense. The variable "Random" isn't set by anything and so checker is always null. Also the %%i% also doesnt make sense.. it should be %%i . I think this could work without using delayed expansion if your description of the problem was a little better. Commented Nov 14, 2011 at 23:53

3 Answers 3

18

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I wrote a Linux shell and I'm trying to transfer it over to Windows batch so I'm a little behind on the syntax. I really appreciate it though. Thanks again!
1

Try by calling a method.

@echo off
pause

for %%i in (*.txt) do (
    call :makeRandom %%i    
)

echo Complete
pause

:makeRandom 
    set /a y = %random%
    echo %y%
    echo %~1 >> backupF 

1 Comment

valid method. Although you should stop the script before the subroutine (goto :eof), else the subroutine will be executed again.
0

on my system I have to write

set checker=Random

instead of

set checker=!Random!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.