Tuesday, February 13, 2024

Yet another reason I learned to hate, but not fear, Windows Batch Scripting

 Consider the following batch script, and save it as "test.bat":

@ECHO OFF
SETLOCAL
:step-1
SET "TEST=0"
Echo TEST before: %TEST%
:step-2
FOR /F "tokens=* USEBACKQ" %%F IN (`ECHO 1`) DO (
  REM step-3
  SET "TEST=%%F"
  ECHO F in loop: %%F
  ECHO TEST in loop: %TEST%
)
:step-4
ECHO TEST after: %TEST%


High-level explanation of each labeled step above,


1. The script sets variable TEST to the value 0.

2. A FOR loop iterates over the value(s) output from the statement "ECHO 1", which predictably yields the single value, "1". We define the placeholder %%F, a special variable to hold each value as we iterate the loop.

3. Inside our FOR loop, we do the following:
   a. Assign the current value of %%F to TEST
   b. Output the current value of %%F
   c. Output the current value of TEST

4. After our FOR loop completes, output the current value of TEST.



Pop-quiz:
What do you expect the output of this batch script to be?