Search code examples
batch-filefor-loopcmddosmkdir

Command Line: Using a for loop to create directories with increasing names


I am trying to write a batch file that does the following:

  1. Prompt user for the directory to create the new folder newest
  2. Prompt user for an integer limit
  3. Create directory newest
  4. CD newest
  5. FOR loop for limit iterations
    • Create directory "Month " + iteration

For example:
newest = Reports
limit = 12
I should end up with:


\Reports\Month 1
\Reports\Month 2
\Reports\Month 3
...
\Reports\Month 12

This is my code so far:

setlocal enabledelayedexpansion
FOR /L %%i IN (1,1,%limit%) DO (
set "month_counter=Month %%i"
echo %month_counter%
MD %month_counter%
)
endlocal

If I set limit = 12, I get 12 error messages stating:

Echo is off.
The syntax of the command is incorrect.

I appreciate the help.


Solution

  • FOR /L %%i IN (1,1,%limit%) DO (
     MD "Month %%i"
    )
    

    You have the standard delayed expansion problem - hundreds of articles on SO about this.

    Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

    Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

    Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

    Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

    So - you could use

    set "month_counter=Month %%i"
    CALL echo %%month_counter%%
    

    If you really, really want to - or one of the other techniques, but it's far easier to simply make the directory from your constant data + the iteration counter in %%i as shown.