Why are environment variables not updating within FOR loop?

前端 未结 1 794
耶瑟儿~
耶瑟儿~ 2021-01-26 12:15

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

相关标签:
1条回答
  • 2021-01-26 12:46
    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

    0 讨论(0)
提交回复
热议问题