Katie Katie - 5 months ago 10
Bash Question

Create n files with random filenames in batch script (Windows) - my script creates only one file

I need to write a batch script, in which I would like to take an argument (lets call it

n
), and create
n
empty files, with random filenames. However, my approach seems not to work, since, it does not create
n
files, but just one:

@echo off

set arg=%1

FOR /L %%i IN (1, 1, %arg%) DO (
set FILENAME=file%RANDOM%.txt
copy /b NUL %FILENAME%
)

pause

Answer

You should use delayed expansion of the variables in the loop, so they become expanded at execution time rather than at parse time:

@echo off
setLocal EnableDelayedExpansion
set arg=%1

FOR /L %%i IN (1, 1, %arg%) DO (
  set FILENAME=file!RANDOM!.txt
  copy /b NUL !FILENAME!
)

pause 
Comments