-1

So, I'm trying to create a batch script that creates a number of files. Number of files to be created is supposed to be specified by user in the first argument as well as the extension for those files in the second argument. Here is the code I got:

@echo on
for /L %%x in (0,1,%1%) do (
    type nul > x%random%.%2%
    echo %1%
    echo %%x
    )

it looks like the loop runs %1 times, however the the random command only works when the loop runs for the first time and never gets updated. Therefore, only one file is created instead of the specified number. Please help me find my mistake, thank you!

jwdonahue
  • 6,199
  • 2
  • 21
  • 43
  • Take the [tour], read [ask] and [mcve]. – jwdonahue Apr 01 '20 at 04:05
  • This is certainly a duplicate, but I am too tired to find any of the previous answers to this question. – jwdonahue Apr 01 '20 at 04:10
  • Even if your code worked, you haven't considered collisions, have you? I mean, what if `random` returns the same value twice... – aschipfl Apr 01 '20 at 06:32
  • You cannot have variables named with single digits like that! `%1%` and `%2%` should most certainly be `%1` and `%2` to represent the first and second arguments. – Compo Apr 01 '20 at 11:00
  • @aschipfl I think it might return the same value, so it it replaces the file every time. How do I fix that though? – Kristina Apr 01 '20 at 15:19
  • Well, a long time ago I once asked a question here: [How to generate a list of random numbers without duplicates in pure batch scripting?](https://stackoverflow.com/q/34406594) – aschipfl Apr 01 '20 at 19:19

1 Answers1

0

Add @setlocal EnableDelayedExpansion to the top of your script and use ! character instead of % around the random variable. Replacement variable look like %1 and %2, not %1% and %2%.

jwdonahue
  • 6,199
  • 2
  • 21
  • 43