1

The functional code is available below:

:: The INDEX control variable is causing the error.
FOR /L %%INDEX IN (%1, %2, %3) DO ECHO %%INDEX

:: Syntax
FOR /L %%parameter IN (start, step, end) DO command

I run this script as follows:

test.bat 0 1 5

I get the following error:

%INDEX was unexpected at this time.

I noticed that this error occurs because of the character count of the control variable (INDEX) in the FOR loop. If I update the INDEX control variable to be a single character (such as X), the program works as expected.

What are the rules for naming a control variable in a FOR loop?

Sercan
  • 4,739
  • 3
  • 17
  • 36
  • 1
    The syntex error hints at your problem. For variables cannot be named, they are single character metavariables – T3RR0R May 16 '22 at 14:22
  • 3
    Not only single-character, but single case-sensitive character. A-Z. Certainly not numeric. *some* symbols work, but are generally avoided as being undocumented. – Magoo May 16 '22 at 14:24
  • 1
    Not for the faint of heart: https://stackoverflow.com/a/56246879/12343998 – T3RR0R May 16 '22 at 14:40
  • 2
    I recommend to read also chapter __issue 7: Usage of letters ADFNPSTXZadfnpstxz as loop variable__ in [this answer](https://stackoverflow.com/a/60686543/3074564) and my answer on [Where does GOTO :EOF return to?](https://stackoverflow.com/a/37518000/3074564) Do not use `GOTO :EXIT`, use `GOTO :EOF` or `EXIT /B` (or `GOTO ENDBATCH` with a label `:ENDBATCH` if there is anything below this label like `ENDLOCAL` or `PAUSE`). – Mofi May 16 '22 at 16:27
  • 1
    It would be also a good idea to read my answer on [Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files](https://stackoverflow.com/a/47386323/3074564) with full explanation of string comparison done with command __IF__. The __IF__ condition as currently written results in an exit of batch file processing because of a syntax error on calling the batch file with `BatName.cmd "Argument 1" "Argument 2" "Argument 3"`. The condition should be `IF "%~3" == "" EXIT /B` to work independent on batch file called with arguments enclosed in `"` or not enclosed in double quotes. – Mofi May 16 '22 at 16:31
  • [This link](https://ss64.com/nt/for.html) has rules for naming parameters in a for loop. Thanks to everyone who helped. – Sercan May 18 '22 at 19:09
  • 1
    Strangely, I'd call it a `control variable` rather than a `parameter`... – Magoo May 18 '22 at 19:19

0 Answers0