Why does this batch file fail on a "REM" line?

The error-msg refers to the commented out second line

This is due to the very complex parsing that is used by cmd to process scripts.

In short the parser processes % before pretty much everything else (phase 1) and throws an error as some of the %s need to be doubled as %% when used in a batch file.

So in a batch file:

for %%F in (*.pdf) do ren "%%~F" "%%~nF OdB%%~xF"

is a valid command and:

REM for %a in (*.txt) do ren "%~a" "%~na version 1%~xa"

is a broken command (the %a should be %%a, etc).

Note that:

REM for %a in (*.txt) do ren "%~a" "%~na version 1%~xa"

is a valid command when run from the command line as then the % does not need to be doubled.

REM would be processed in phase 2 of the parser, but it never gets there as the % processing in phase 1 has already generated an error and terminated the parsing.

For all the gory details of the cmd parser please read parsing - How does the Windows Command Interpreter (CMD.EXE) parse scripts? - Stack Overflow


It doesn't work because even though it is "remarked" it is evaluated for substitutions, and then apparently discarded.

For "batch" your second line is incorrect and should read

REM Rework 2020-12-16
REM for %%a in (*.txt) do ren "%%~a" "%%~na version 1%%~xa"
for %%F in (*.pdf) do ren "%%~F" "%%~nF OdB%%~xF"

The corrections being that in batch programming expansions need to have %% rather than a single %.


To add to the existing answers, although REM is used for comments, it is important to understand that it is actually a command that does nothing, not a comment. This is different from a Unix shell, where you have real comments and can add arbitrary text after a # character.

Not only the substitutes are evaluated for the REM command, also file redirects. So beware that the following line will delete the content of the file, because the REM command produces no output, but the empty output will be redirected to the file

REM some_command > important_file

Edit

As a comment pointed out, this is no longer true for modern Windows versions. According to https://stackoverflow.com/a/4095133/10765659 there is now special handling of REM so that redirections are not executed, but this special handling occurs too late to make REM a true comment, as the substitutes are still evaluated.