1
votes

I am new to batch programming.

The output of the following program:

@ECHO OFF
cd /d C:%HOMEPATH%\AppData\Roaming\Mozilla\Firefox\Profiles
echo %cd%
FOR /F %%i IN (temp_list.txt) DO (
 echo i is %%i
 cd folder
 echo %cd%
)
cd folder
echo %cd%
pause

is:

C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles
i is e6slask2.default
C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles
i is random.default
The system cannot find the path specified.
C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles
The system cannot find the path specified.
C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles\folder
Press any key to continue . . .

I understand that the FOR logic is wrong (i effectively am doing cd folder twice, should be possible only unless there is a 'folder' inside a 'folder')
but why isn't the cd folder taking me to the "C:\Users\abhagaba.ORADEV\AppData\Roaming\Mozilla\Firefox\Profiles\folder" for the first iteration in the FOR loop?

Does CD not work inside a FOR loop?

1

1 Answers

2
votes

First thing first, batch don't update variables inside a code block, but there must be a way to solve it. That's why Setlocal EnableDelayedExpansion is pretty useful once working with for/if commands. The code will look like:

@ECHO OFF
Setlocal EnableDelayedExpansion

cd /d C:%HOMEPATH%\AppData\Roaming\Mozilla\Firefox\Profiles
echo %cd%
FOR /F %%i IN (temp_list.txt) DO (
    echo i is %%i
    cd folder
    echo !cd!
)
cd folder
echo %cd%
pause

Replace percent signs with exclamation marks (%var% -> !var!) will solve your problem. Don't worry about variables outside the code block, using old-style %var% will not affect the result.