Franz Ebner
Franz Ebner

Reputation: 5096

Iterate over a array of folders in batch

I try to iterate over an array of strings representing siblings inside a common parent folder.

When I try to enter the first sibling "a", my path check fails and the program terminates. After the termination I end up within the first sibling though.

set dir="C:\somepath\"
set subdir[0]="a"
set subdir[1]="b"

cd %dir%

for /F "tokens=2 delims==" %%s in ('set subdir[') DO (
    cd %%s

    set sub=%dir%%%s
    if %CD% neq [%sub%] exit /b 1

    echo %%s

    cd ..
)

For me, it seems like the %CD% variable isn't changed right after the change of cd but I wasn't able to reproduce this suspicion like this:

cd a
echo %CD%
cd ..

I'm trying hard since a couple of ours ago now - without success.
Can anyone give me a hint?


Edit:

Took me some more 'minutes' but it works like a charm now.

Setlocal EnableDelayedExpansion

set dir="C:\somepath\"
set subdir[0]="a"
set subdir[1]="b"

for /F "tokens=2 delims==" %%s in ('set %~2 [') DO (
    cd %%~s
    set sub=!dir:~1,-1!%%~s

    if [!CD!] neq [!sub!] exit /b 1

    echo !CD!       
    cd ..
)

Upvotes: 0

Views: 858

Answers (1)

npocmaka
npocmaka

Reputation: 57252

Not pretty sure about your logic (especially the comparison ) , but you need delayed expansion:

setlocal enableDelayedExpansion
set dir="C:\somepath\"
set subdir[0]="a"
set subdir[1]="b"

cd %dir%


for /F "tokens=2 delims==" %%s in ('set subdir[') DO (
    cd %%s

    set sub=!dir!%%s
    if [!CD!] neq [!sub!] exit /b 1

    echo %%s

    cd ..
)

Upvotes: 2

Related Questions