/errors/cmd/the-syntax-of-the-command-is-incorrect
cmd: The syntax of the command is incorrect.
- tool
- Command Prompt (cmd)
- exit code
- 255
- versions
- Windows 10, Windows 11, Windows Server 2016+
- os
- windows
The syntax of the command is incorrect. means cmd could not parse the line after variables were expanded. In batch files the usual cause is an if test on a variable that is empty, so if %ANSWER%==yes becomes if ==yes or if x==. Quote both sides: if "%ANSWER%"=="yes". Like other parse errors, it stops the whole batch file, not only the line.
Reproduce it
Each case runs in its own small batch file, because a syntax error ends the batch that contains it:
> bad1.cmd echo @if x==
cmd /d /c bad1.cmd 2>&1
echo bad1: ERRORLEVEL=%ERRORLEVEL%
> bad2.cmd echo @set "ANSWER="
>> bad2.cmd echo @if %%ANSWER%%==yes echo y
cmd /d /c bad2.cmd 2>&1
> good.cmd echo @set "ANSWER="
>> good.cmd echo @if "%%ANSWER%%"=="yes" (echo y) else (echo not yes)
cmd /d /c good.cmdOutput
The syntax of the command is incorrect. /tmp/work>@if x== bad1: ERRORLEVEL=255 echo was unexpected at this time. /tmp/work>@if ==yes echo y not yes
The first file fails with this message and ERRORLEVEL 255. With an empty variable the error text depends on what follows the comparison, which is why the same bug also shows up as echo was unexpected at this time.. Quoting both sides fixes both.
Debug a batch file
- Remove or comment out
@echo off(rem @echo off) and run the file from an open Command Prompt, not by double-clicking. cmd prints each line after expansion; the last line printed is the one that failed. - Print the variables used on that line (
echo [%ANSWER%]) to see empty values or stray quotes. - For blocks in parentheses, check the balance. A
)inside anechowithin a block closes it: writeecho Done ^(ok^).
Fragile lines and safer forms
These lines work while the values are set and fail with a parse error (this one or ... was unexpected at this time.) as soon as a value is empty or contains spaces or parentheses:
| Fragile | Safer |
|---|---|
| if %1==-v goto verbose | if "%~1"=="-v" goto verbose |
| if exist %FILE% ( | if exist "%FILE%" ( |
| if %COUNT% GTR 5 echo many | if not defined COUNT set COUNT=0 first |
| for %%f in *.txt do ... | for %%f in (*.txt) do ... |
| echo Done (ok) inside a block | echo Done ^(ok^) |