variablesbatch-fileinputunassigned-variable

Variable not being assigned first time from input in a batch script


So I am trying to ask the user if they want to overwrite a current virtual machine if one already exists. I have extracted the problem part of this .bat file into a separate file to replicate the problem.

The code from this file is:

@echo off
@setlocal enabledelayedexpansion

SET test=blah
SET existingMachines=blahsdg

:checkOverwrite
if not "%test%"=="%existingMachines%" (
    SET /P machineOverwrite="A machine containing this name already exists. Do you want to overwrite it (y/n)? "
    if /I "%machineOverwrite%"=="y" (
        echo overwrite
    ) else (
        if /I "%machineOverwrite%"=="n" (
            echo You will need to choose a new name for your virtual box or overwite the existing one.
        ) else (
            echo WARNING: You did not enter y or n
            GOTO :checkOverwrite
        )
    )
)

pause

The concept is the first if will always come back as true (as these variables are never equal in this case) and from there it would ask if they want to overwrite the machine. If they say "y", you should see "overwrite" and then press any key to continue...

The issue is it's not doing that! Its doesn't seem to be setting the machineOverwrite variable, and so it is going through to the "you did not enter y or n" section. From here it goes back to the start, and goes through again.

The REAL strange thing is that the next time you go through, if you choose "y", it does what its meant to! BUT, if you choose "n", it still does what it should with "y"!

Every time I enter anything, it always get the input from before it went back to :checkOverwrite and not the latest input. WHY??


Solution

  • Your problem is that despite attempting to enable delayed expansion (with setlocal enabledelayedexpansion) you aren't actually using it.

    %var% is normal variable expansion, even with delayed expansion turned on.

    You need to use !var! for delayed variable expansion. See (for example) the "documentation" here.