Variables acting very wierd - New to batch programming

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
joev68
Posts: 2
Joined: 11 Sep 2007 13:29

Variables acting very wierd - New to batch programming

#1 Post by joev68 » 11 Sep 2007 13:46

Simple code

-----1.BAT-------
set outdir=%1
FOR /D %%F IN (%outdir%) (
set dir1=%%F
echo %dir1%
)
---------------------

I have c:\new
c:\new\1 <DIR>
c:\new\2 <DIR>
c:\new\3 <DIR>

when I execute it like this
C:\> 1.BAT \new\*.*

its assigning set dir1=\new\1
echo \new\3

set dir1=\new\2
echo \new\3

set dir1=\new\3
echo \new\3

Why is it not showing me \new\1 and \new\2 and \new\3 in the echo statements. Please help.

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#2 Post by DosItHelp » 12 Sep 2007 23:49

joev68,

The problem is that the command interpreter reads the whole FOR block, expands the %variables% and then executes the block, which means in your case the %dir1% will not be expanded for each directory found as you might expect but only once before the block is being executed.

Here two solutions:
1) use delayed expansion for variables:

Code: Select all

setlocal ENABLEDELAYEDEXPANSION
set outdir=%1
FOR /D %%F IN (%outdir%) do (
   set dir1=%%F
   echo.!dir1!
)


2) force the command interpreter to expand the variable by opening a new command context:

Code: Select all

set outdir=%1
FOR /D %%F IN (%outdir%) do (
   set dir1=%%F
   call echo.%%dir1%%
)



DOS IT HELP? :wink:

joev68
Posts: 2
Joined: 11 Sep 2007 13:29

Thanks, DosITHelp

#3 Post by joev68 » 14 Sep 2007 07:15

Thats work well. Thank you so much.

Post Reply