Search code examples
batch-filecmdgoto

cmd error: goto was unexpected at this time


Im just learning how to code in cmd, but for some reason, the tutorials that are out there aint working on my computer. I was trying to run the following program, but it just keeps failing on me.

::My first program

@echo off
:main menu
cls
echo what are you doing?
echo.
echo 1) Nothing :-P
echo 2) dancing
echo. 
set /p var="Choose answer:" 
if %answer% == 1 goto nothing
if %answer% ==2 goto dancing

:nothing
echo ok...chill

:dancing
echo nice

echo on

Solution

  • As others have pointed out here, your problem is that you set a variable called var and then tried to read a variable called answer. The root fix is to pick one name and stick with it. However, I want to offer two other pointers.

    First, when debugging your batch file, remove the line @echo off from the top of your file. With echo on, you can see exactly which line was executing when you got your error, which will point you to the solution much more quickly.

    Second, the reason your batch file terminated was a syntax error. With the answer variable unset, your if statement evaluated to

    if == 1 goto nothing
    

    This is not valid batch syntax, which is what caused the error "goto was unexpected at this time", and caused your batch file to terminate. Your code will still get this error if the user enters a blank string, even after fixing the issue of the wrong variable name. To correctly handle empty variables in an IF statement, place brackets or quotes around each side of the == like this:

    if [%answer%]==[1] goto nothing
    

    This way, even if the variable is the empty string, the IF evaluates to if []==[1] goto nothing, which is still a valid statement and thus won't crash your script.