tran phan anh khoa
tran phan anh khoa

Reputation: 3

Cannot use !random! in batch file

@echo off
setlocal enableDelayedExpansion

set /p startIndex="Start index: "
set /p endIndex="End index: "

for /l %%a in (%startIndex% 1 %endIndex%) do (
    set /a seed = !random!
    echo %seed%
)
set /p endfile="Wait for it...."

I expect that this script will print out some random numbers. But it does not work. It just printed out some lines with same content: "Echo is off ."

How can I fix this code ?

Upvotes: 0

Views: 157

Answers (2)

Mofi
Mofi

Reputation: 49096

Delayed expansion is also required on referencing the value of variable seed defined and assigned with a random value within a block defined with ( ... ).

@echo off
setlocal EnableDelayedExpansion

set /p "startIndex=Start index: "
set /p "endIndex=End index: "

for /l %%a in (%startIndex% 1 %endIndex%) do (
    set "seed=!random!"
    echo !seed!
)
set /p "endfile=Wait for it ..."

Further option /a is not necessary to assign a random number to variable seed as no arithmetic expression to evaluate. But be careful with spaces around equal sign. All spaces are ignored by set on using option /a, but are not anymore ignored by command set on a simple assignment without option /a.

And also take care about where first double quote is written on line with command set as this makes a big difference.

For details about spaces around equal sign and first double quote position see answer on
Why is no string output with 'echo %var%' after using 'set var = text' on command line?

Upvotes: 1

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11631

You need to say

echo !seed!

because the whole loop is parsed at the beginning, and seed is expanded (to nothing, as it doesn't exist yet) before the loop starts running. You therefore need to use delayed expansion.

Upvotes: 2

Related Questions