0

I have a batch file that is scanning a file URLs.txt and for each url run it and download the file. The issue I have is the environment variable within the FOR loop. I am using cat, sed and awk to get the last two parts of the the url so I can provide the filename. The issue is the environment variable is never updated after the first run. I can see that tmp2.txt just updated correctly for every url, but the batch file is not updating outfile and thus I keep overwriting the first file.

I tried to simplify the batch file for a test and any variable within a for loop never seems to update.

@echo off
setlocal enabledelayedexpansion

for /F "tokens=*" %%A in (URLs.txt) do (
    echo %%A > tmp.txt
    cat tmp.txt | sed "s/\(.*\)\//\1_/" | awk -F "/" "{print $NF}" > tmp2.txt
    set /p outfile=<tmp2.txt
    echo Varible A
    echo %%A
    echo.
    echo Varible outfile
    echo %outfile%
    call curl.exe -o %outfile% -u username:password --insecure %%A
    pause
)

Why is environment variable outfile not updated within FOR loop?

1
  • 5
    Ah, the classic "you're using delayed expansion, but you're not using delayed expansion." It happens more than you might think. Commented Oct 31, 2016 at 2:13

1 Answer 1

4
echo !outfile!

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

In your case, since outfile is assigned the value %%A, you can replace %outfile% with %%A - and it would be an idea to "quote the string" anyway since "quoting a string" makes it a single token rather than a series - just in case your filenames contain separators like Space

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

Comments

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.