This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
48} Why do some comment lines cause errors? What can I do about it?
Consider the following script
@echo off & setlocal enableextensions
rem set var2=%~var1%
echo We made it!
endlocal & goto :EOF
While the above should work (the second, syntactically incorrect line
is just a comment) the output will be
D:\TEST>cmdfaq
The following usage of the path operator in script-parameter
substitution is invalid: %~var1%
For valid formats type CALL /? or FOR /?
The syntax of the command is incorrect.
Now why is this? I do not know. I can only speculate. It would
appear that a command line is parsed from the end towards the
beginning. If so, the error is reported before the REM comment
command is reached. That obviously is a bug in the Microsift
NT/2000/XP/../Win10 CMD.EXE command line processor parser.
The
following alternatives cause the same error
@echo off & setlocal enableextensions
:: set var2=%~var1%
echo We made it!
endlocal & goto :EOF
and (c.f.
Item #9)
@echo off & setlocal enableextensions
rem set var2=%~var1%> nul 2>&1
echo We made it!
endlocal & goto :EOF
What can one do about it? The only solution I currently know is an
ugly one:
@echo off & setlocal enableextensions
goto _afterComment
rem set var2=%~var1%
:_afterComment
echo We made it!
endlocal & goto :EOF
Now the output will be as it should:
D:\TEST>cmdfaq
We made it!
To still demonstrate that the
%~ is at
the core of the backwards-parsing catch:
@echo off & setlocal enableextensions
rem
%~
echo We've made it
endlocal & goto :EOF
D:\TEST>cmdfaq
The following usage of the path operator in batch-parameter
substitution is invalid: %~
For valid formats type CALL /? or FOR /?
The syntax of the command is incorrect.
while
@echo off & setlocal enableextensions
rem %
^~
echo We've made it
endlocal & goto :EOF
D:\TEST>cmdfaq
We've made it
Another similar catch
@echo off & setlocal enableextensions
(
:: Note the empty line below
echo We've made it
)
endlocal & goto :EOF
D:\TEST>cmdfaq
The syntax of the command is incorrect.
while
@echo off & setlocal enableextensions
:: Note the empty line below
echo We've made it
endlocal & goto :EOF
D:\TEST>cmdfaq
We've made it
and
@echo off & setlocal enableextensions
(
rem Note the empty line below
echo We've made it
)
endlocal & goto :EOF
D:\TEST>cmdfaq
We've made it
Add to all this the fact that so many
and
constructs cause confusion and elicit questions. - One can't easily
second-guess the backwards-parsing cmd.exe interpreter.