For loops: Is there any reason you HAVE to use different tokens?
Posted: 2023-Mar-20, 8:01 am
The other day while looking for something else, I stumbled across a web page where a user stated that since some other characters can be used as tokens in a For loop, it was possible to create more than 26 nested loops.
The thing is that, other than for readability, there doesn't seem to be any need to use different tokens at all. Tokens only retain their value within a loop, and since a loop needs to complete before the rest of the script continues, that loop is finished when control passes back to the loop above it. And since the child loop's token no longer exists, the parent loop's token is used.
This works perfectly fine;
It reads each matching file, echoes its name, echoes each line of the file, echos the numbers 1-3, echoes the line again, then does the same thing for the next line, echoing the filename again at the end, before proceeding to the next file.
You'd think that the second loop would screw up, since it uses %%F as both a token and a parameter, but no, it works just fine.
I'll admit that this is a bad example, but despite all three loops using %%F as the token, they all print exactly what they're supposed to print.
Granted, such code would be confusing when using multiple, nested loops, but as far as I can see, there's no valid reason that you can't use the same token for every loop.
The thing is that, other than for readability, there doesn't seem to be any need to use different tokens at all. Tokens only retain their value within a loop, and since a loop needs to complete before the rest of the script continues, that loop is finished when control passes back to the loop above it. And since the child loop's token no longer exists, the parent loop's token is used.
This works perfectly fine;
Code: Select all
@echo off
for %%F in (file*.txt) do (
echo %%F
for /f "delims=" %%F in (%%F) do (
echo %%F
for /l %%F in (1,1,3) do echo %%F
echo %%F
))
You'd think that the second loop would screw up, since it uses %%F as both a token and a parameter, but no, it works just fine.
I'll admit that this is a bad example, but despite all three loops using %%F as the token, they all print exactly what they're supposed to print.
Granted, such code would be confusing when using multiple, nested loops, but as far as I can see, there's no valid reason that you can't use the same token for every loop.