Random variable not changing in “for” loop in windows batch file

后端 未结 2 1237
无人及你
无人及你 2020-12-06 11:05

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 (*         


        
相关标签:
2条回答
  • 2020-12-06 11:20

    on my system I have to write

    set checker=Random
    

    instead of

    set checker=!Random!
    
    0 讨论(0)
  • 2020-12-06 11:27

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

    0 讨论(0)
提交回复
热议问题