2

I am confused at how to access array values from inside a for loop in a windows batch file. Here is my test:

@ echo off
SET ROOT=c:\temp\test

REM set up array of local dir paths
SET LDIR[1]=data
SET LDIR[2]=data\fonts
SET LDIR[3]=data\images

for /L %%s in (1,1,3) do (
  IF EXIST %ROOT%\%%LDIR[%%s]%% (
    call echo %ROOT%\%%LDIR[%%s]%% exists
  ) else (
    call echo %ROOT%\%%LDIR[%%s]%% does not exist
  )
)

I get output:

c:\temp\test\data does not exist
c:\temp\test\data\fonts does not exist
c:\temp\test\data\images does not exist

even though the dirs exist. I believe the array is not getting derefernced correctly in the IF EXISTS statement. What is the correct way to do this? Also Why is it necessary to use "call" to get the array to dereference correctly? --Thanks!

webcoyote
  • 25
  • 4

1 Answers1

1
@ echo off
SET ROOT=c:\temp\test

REM set up array of local dir paths
SET LDIR[1]=data
SET LDIR[2]=data\fonts
SET LDIR[3]=data\images
setLocal enableDelayedExpansion
for /L %%s in (1,1,3) do (
  IF EXIST %ROOT%\!LDIR[%%s]! (
    echo %ROOT%\!LDIR[%%s]! exists
  ) else (
    echo %ROOT%\!LDIR[%%s]! does not exist
  )
)
endLocal

The problem is that you need to "call" the if in the same manner as your ECHOes but the IF command cannot be used with CALL so your last hope is delayed expansion.In this way also your performance will be boosted as there's no need of CALL

webcoyote
  • 25
  • 4
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • This works correctly. Yes 'setLocal enableDelayedExpansion' is the key as well as the correct !LDIR[%%s]! – webcoyote Jun 17 '14 at 16:04