Page 1 of 1

Variables acting very wierd - New to batch programming

Posted: 11 Sep 2007 13:46
by joev68
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.

Posted: 12 Sep 2007 23:49
by DosItHelp
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:

Thanks, DosITHelp

Posted: 14 Sep 2007 07:15
by joev68
Thats work well. Thank you so much.