Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch: FOR /R doesn't work with a variable in the path

An example:

FOR %%i IN (3) DO (
    ECHO %%i
    FOR /R "C:\backup\server%%i\temp" %%? IN (*.bak) DO (
        REM some code...
    )
)

Result of ECHO: 3.

Result of second FOR: the code isn't executed.

But with:

FOR %%i IN (3) DO (
    ECHO %%i
    FOR /R "C:\backup\server3\temp" %%? IN (*.bak) DO (
        REM some code...
    )
)

Result of ECHO: 3.

Result of second FOR: the code is executed.

Any idea?

like image 502
GG. Avatar asked Dec 28 '22 08:12

GG.


1 Answers

The reason the original code does not work is because the directory for the FOR /R option must be known at the time the FOR is parsed, but the %%i variable is not expanded until after the FOR statement has already been parsed. The same problem exists for the adarshr suggestion - !suffix! is not expanded until after the FOR statement has been parsed.

The GG answer is a very good viable work-around. Perhaps could be improved with PUSHD followed by POPD at end, instead of CD. But only if needed.

The only other way I can think to get around the problem is something like this

@echo off
FOR %%i IN (3) DO call :innerLoop %%i
exit /b

:innerLoop
FOR /R "C:\backup\server%1\temp" %%? IN (*.bak) DO (
  REM some code...
)
exit /b

But I don't like to use CALL unless I have to because it is inefficient. I like the CD solution.

like image 195
dbenham Avatar answered Jan 10 '23 09:01

dbenham