Issue With For Loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
whizkid667
Posts: 2
Joined: 23 May 2012 09:56

Issue With For Loop

#1 Post by whizkid667 » 23 May 2012 10:06

I wrote a batch file to recursively create subfolders, based on the data taken from a list.

Code: Select all

set BackupFileDir=BackupFiles

if not exist %BackupFileDir% mkdir %BackupFileDir%

for %%x in (A1 B2 C3) do (
   echo %%x >>Log.log
   set MyFolder=%%x
   echo %MyFolder% >>Log.log
   set ActualDiffFolder=%BackupFileDir%\%MyFolder%
   
   mkdir %ActualDiffFolder%
)

pause


Am getting the error that mkdir failed.
When I logged out, I found that while logging %%x is got the Correct Value
But MyFolder which is assigned the same value as %%x is not logging anything.
That means, no parameters are passed for mkdir

The log file is like this

Code: Select all

A1 
ECHO is on.
B2
ECHO is on.
C3
ECHO is on.


Is there any issue with assigning variables inside for loop?

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: Issue With For Loop

#2 Post by Squashman » 23 May 2012 10:12

This usually requires you to enable delayed expansion and use an exclamation around your variable names instead of a percent sign.

But why bother assigning the variables like you are doing. You can just use them as is without using delayed expansion.

Code: Select all

set BackupFileDir=BackupFiles

if not exist %BackupFileDir% mkdir %BackupFileDir%

for %%x in (A1 B2 C3) do (
   echo %%x >>Log.log
   mkdir %BackupFileDir%\%%x
)

pause


If you want to use your original script.

Code: Select all

set BackupFileDir=BackupFiles

if not exist %BackupFileDir% mkdir %BackupFileDir%

for %%x in (A1 B2 C3) do (
   setlocal enabledelayedexpansion
   echo %%x >>Log.log
   set MyFolder=%%x
   echo !MyFolder! >>Log.log
   set ActualDiffFolder=%BackupFileDir%\!MyFolder!
   
   mkdir !ActualDiffFolder!
   endlocal
)

pause

whizkid667
Posts: 2
Joined: 23 May 2012 09:56

Re: Issue With For Loop

#3 Post by whizkid667 » 24 May 2012 00:16

Thanks a lot Squashman for the prompt reply.
Worked like a charm :)

Post Reply