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!

3
  • Did you try IF "%SVNROOT%\%%LDIR[%%s]%%" ? Commented Jun 16, 2014 at 17:43
  • I suggest you to see this post Commented Jun 16, 2014 at 22:40
  • Aacini, yes this is an excellent link, Thank you! Commented Jun 17, 2014 at 16:00

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This works correctly. Yes 'setLocal enableDelayedExpansion' is the key as well as the correct !LDIR[%%s]!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.