Search code examples
batch-filegoto

Batch goto keeps giving me the same output?


Here is the code I am using:

@echo off

:default
set /p cmd= "1 or 2"
if %cmd%=="1" goto one
if %cmd%=="2" goto two

:one
echo "1 worked"
goto default

:two
echo "2 worked"
goto default

However, the output I get is "1 worked" no matter what I put in. Does anyone know what I'm doing wrong?


Solution

  • Your issue is that you're ignoring the doublequotes. Unless the end user inputs "1" or "2" both sides of the comparison == will never match, and your code will always fail both if commands and continue on to :one. The fix is to ensure that both sides of the comparison are doublequoted.

    This shows you how it should have worked, but please note that the end user can enter absolutely anything they want at the prompt, so you should technically perform some validation on that input before trying to use it. The best way is to instead use a more robust input method such as the choice command

    This example uses your not recommended Set /P method:

    @Echo Off
    
    :default
    Set "num="
    Set /P "num=1 or 2"
    If "%num%" == "2" GoTo two
    If Not "%num%" == "1" GoTo default
    Echo "1 worked"
    GoTo default
    
    :two
    echo "2 worked"
    GoTo default
    

    Note, I changed your variable name from cmd, as it is confusing to use command names as variable names.


    This uses the recommended Choice command instead:

    @Echo Off
    
    :default
    "%__AppDir__%choice.exe" /C 12
    If ErrorLevel 2 GoTo two
    Echo "1 worked"
    GoTo default
    
    :two
    Echo "2 worked"
    GoTo default
    

    Alternatively you could use the error level as your GoTo:

    @Echo Off
    
    :default
    "%__AppDir__%choice.exe" /C 12
    GoTo Label%ErrorLevel% 2>NUL||GoTo default
    
    :Label1
    Echo "1 worked"
    GoTo default
    
    :Label2
    Echo "2 worked"
    GoTo default