rschirin
rschirin

Reputation: 2049

Batch failure set value to a variable

this is my code:

@echo off
Setlocal EnableDelayedExpansion

set log=C:\mylog.log

set ftpFolder=C:\contributor\ftp
set rotterdamFolder=C:\rotterdam

cd /D C:\contributor
echo [FTP Folder: %ftpFolder%] >> %log%
cd /D %ftpFolder%

for /D %%f in (*) do (
cd %%f
for %%i in (*) do (     
    echo [FTP, %%f] Sending %%i >> %log%
    for /f "tokens=1,2" %%a in (C:\input.txt) do (
        if %%a==%%f ( 
            set et=%%b              
            )
        )
    copy %ftpFolder%\%%f\%%i %rotterdamFolder%\%et% >> %log%
)
cd .. >> %log%
)

input.txt file is something like:

007   87855
008   87823
015   87830

it's not important how the two columns are divided (tab or space). my problem is that %et% variable is not defined. how is it possible? I need to use variable "b" as destination folder. where is the error?

Upvotes: 1

Views: 66

Answers (1)

dbenham
dbenham

Reputation: 130879

%et% is expanded when the line is parsed, and the entire outer parenthesized FOR loop is parsed all at once. So the value you get is the value that existed before your loop was entered.

You could solve the problem by enabling delayed expansion and using !et! instead. Type HELP FOR or FOR /? from the command line for more information. The section about delayed expansion is about halfway down.

But there really isn't any need to use the et variable at all. I believe you only want to copy the file when the first column of the inner loop matches the folder name. Simply move and substitute the COPY command for the SET statement. Use %%b instead of %et% in the COPY statement.

It wasn't necessary, but I substituted PUSHD/POPD for the CD commands. The redirection with CD is pointless when a path is specified.

You really should quote your paths in case they contain spaces or special characters.

for /D %%f in (*) do (
  pushd "%%f"
  for %%i in (*) do (     
    echo [FTP, %%f] Sending %%i >> %log%
    for /f "tokens=1,2" %%a in (C:\input.txt) do if "%%a"=="%%f" (
      copy "%ftpFolder%\%%f\%%i" "%rotterdamFolder%\%%b" >> %log%
    )
  )
  popd
)

Upvotes: 2

Related Questions