Problem with user input in my batch file

2019-01-28 10:58发布

问题:

here is the portion of code giving me trouble:

IF EXIST TH_BUILD_* (
ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 
if "%delBuild%"=="y" (GOTO deleteandcontinue) else ( EXIT)
)

For some reason, no matter the input, the batch file exits. Why is this happening (deleteandcontinue is never reached)?

Thanks!

回答1:

Try using delayed expansion when testing delBuild:

setlocal enableextensions enabledelayedexpansion

IF EXIST TH_BUILD_* (
    ECHO A current build of Test Harness exists.
    set /p delBuild=Delete preexisting build [y/n]?: 
    if "!delBuild!"=="y" (
        GOTO deleteandcontinue
    ) else (
        exit
    )
)

:deleteandcontinue
@echo At deleteandcontinue

%var% variables are expanded when the command is read. The set of commands between the parens are treated as a single command, so delBuild doesn't exist when you go to test. With the delayed expansion, the variables are expanded when the command is executed, so at the time of the test, delBuild has a value.