baz was unexpected at this time.
What happened here?
Well, look at the following code:ECHO command
to end? Right, just before the closing paren. Let's rewrite that line:
IF
block?A straightforward idea of writing this would be
ECHO tells us
that it prints the whole line, unless interrupted by things like & or >. And of
course ECHO :-) works just
fine from the command line. Put into an IF block,
however, yields an error:
IF block,
kinda like the first */ will end a comment in C.
Cmd's behavior here makes sense for single-line IFs but in
my opinion it is a bit annoying when going multi-line.Now we know what to look
for, it'd be nice to know how to prevent this in future. The first idea would be
to move the interior of the block in a subroutine:
^, so the
code would look the following:
Note, that if you have the parentheses in a variable (such as the 32-bit program files directory on x64 systems), then you need to either use delayed expansion or a subroutine (to avoid the parentheses).
Things to learn from this: The escape character is applicable anywhere in batch files. It causes every character to be recognized as not being part of the syntax.
Comments
Parameterizing for loops with parameters containing parentheses
When the parentheses are passed within some parameter or variable into a for loop such as this one in a cmd script:
for /f „usebackq tokens=1–5“ %%S in (
sc %PAR%) DO (IF /I [„%%U“] EQU [„FAILED“] (endlocal & exit /b %%V))where in this case %PAR% may be an SDDL string containing parentheses – even escaping them won't help. The escaping is gone when the %PAR% is replaced with the parameters content and breaks the for loop when it is finally executed.
Does anybody know a way around this?