Introduction
When using the SET command in loops it can be seen that the variable is not updating properly.
@echo off
REM count to 3 storing the results in a variable
set tst=0
FOR /L %%f in (1,1,3) Do (set /a tst+=1 & echo. test %%f in loop = %tst%)
echo. Test outside the loop = %tst%
The result of this batch file is
test 1 in loop = 0
test 2 in loop = 0
test 3 in loop = 0
Test outside the loop = 3
Surely the variable tst should be increasing throught the loop?
The answer is that it is! But what happens is that variables are expanded or evaluated just once per command line so multi-line commands such as IF and FOR do not appear to evaluate properly but once the variable is seen outside of their structure the variable is correct.
By using SETLOCAL EnableDelayedExpansion and referencing the variable between ! marks in the loop then the variable now displays correctly...
@echo off
setlocal EnableDelayedExpansion
REM count to 3 storing the results in a variable
set tst=0
FOR /L %%f in (1,1,3) Do (set /a tst+=1 & echo. test %%f in loop = !tst!)
echo. Test outside the loop = %tst%
The result of this batch file is
test 1 in loop = 1
test 2 in loop = 2
test 3 in loop = 3
Test outside the loop = 3
The ! Marks Are Important!
Take a look at this code that looks for a partocular text on a couple of web pages.:
@echo off
setlocal enabledelayedexpansion
set sitename[0]=Example
set siteURL[0]=https://example.com/index.html
set sitename[1]=Ray's Miscellany Home
set siteURL[1]=https://brisray.com/index.html
set sitename[2]=Ray's Miscellany Webrings
set siteURL[2]=https://brisray.com/utils/webrings.htm
set searchtext=computering/onionring-variables.js
FOR %%G IN (0,1,2) DO (
curl -s -L !siteURL[%%G]! > %TEMP%\webpage.txt
findstr /C:%SEARCH_TEXT% %TEMP%\webpage.txt >nul
IF !errorlevel!==0 (
set result=found
) else (
set result=not found
)
echo !sitename[%%G]! - !siteURL[%%G]! - !result! >> checkURLs.txt
)
setlocal
del %TEMP%\webpage.txt
In the above code, unless the ! delimiters are used, or if the the usual % delimiters are, then the errorlevel does not change and so the script will fail in all cases.