1

I am trying to comment out some useful hints. I followed this Stack Overflow page to apply the most defensive comment - using double quotes. Comment error. But I still get error

This is my simple script: test_comment.cmd

@echo off

:: "   %~nI        - expands %I to a file name only "
:: "   %~xI        - expands %I to a file extension only "
for /F "delims=" %i in ("c:\foo\bar baz.txt") do @echo %~nxi

This is the error I got when I run it

>test_comment
The following usage of the path operator in batch-parameter
substitution is invalid: %~nI        - expands %I to a file name only "


For valid formats type CALL /? or FOR /?
The syntax of the command is incorrect.

If I removed those two commented lines, error would disappear; so that I know the comment didn't work.

How should I comment out those two lines?

I really don't want to delete them.

I am using windows 10, latest patch, default cmd.exe.

oldpride
  • 761
  • 7
  • 15
  • Did you also try using `REM` instead of `::`? – SomethingDark Sep 02 '22 at 20:34
  • yes. I used REM too, but didn't help. In my case, according to the link, :: is better than REM as REM is a command by itself. – oldpride Sep 02 '22 at 20:35
  • 5
    Use `%%` in place of `%`. In a batch file, `%%` is more correct in any case, as `%~nI` is only valid at the prompt. `rem` is better that `::` because it always works, whereas `::`breaks code blocks (parenthesised sequences of lines), Unfortunately, `REM` is more intrusive visually. – Magoo Sep 02 '22 at 20:48
  • 5
    [dbenham's description](https://stackoverflow.com/a/7970912/2152082) at least tells you *why* it fails (especially `Phase 1.2` and `Note 1`). – Stephan Sep 02 '22 at 21:19
  • 2
    Note, that `::` is not a comment but a broken label; the `rem` command is the way to define a true comment or remark… – aschipfl Sep 03 '22 at 08:02

1 Answers1

2

I followed the link in @Stephan's comment and read: Batch Line Parser

Phase 0) Read Line:

Phase 1) Percent Expansion:

Phase 2) Process special characters, tokenize, and build a cached command block

In short: Comment is parsed in Phase 2, after the Percent Expansion in Phase 1.

Solution: use % to escape the % in the comment, as suggested by @Magoo in the comment.

@echo off

:: "   %%~nI        - expands %%I to a file name only "
:: "   %%~xI        - expands %%I to a file extension only "
for /F "delims=" %%I in ("c:\foo\bar baz.txt") do @echo %%~nxI

Then I got the desired result

>test_comment
bar baz.txt
oldpride
  • 761
  • 7
  • 15