我有以下批处理文件代码:
@echo off
SET INSTALL_PATH=c:\program files\
:ask_again
if exist "%INSTALL_PATH%" (
SET /P PATH_EXISTS_ANSWER=Path exists, overwrite?[y/n/default:n]
if not defined PATH_EXISTS_ANSWER (
echo You chose default action^(N^). Try another installation path.
echo.
goto default
)
if /I "%PATH_EXISTS_ANSWER%"=="n" (
echo You chose not to use existing folder. Try another installation path.
echo.
goto noc
)
if /I "%PATH_EXISTS_ANSWER%"=="y" (
echo You chose to overwrite existing folder. Existing files will be overwritten.
echo.
goto yesc
)
echo Please choose Y or N
echo.
goto ask_again
)
:yesc
echo you said yes
goto end
:default
echo you said default
goto end
:noc
echo you said no
goto end
:end
当我选择默认操作时只需按 Enter 就可以了。但是当我使用 N 或 Y 键时,PATH_EXISTS_ANSWER 的值似乎未定义,脚本进入另一个循环,然后,无论我回答什么,脚本都会使用以前的答案。 例如,如果我回答 Y 脚本再次询问,如果我选择 N,它会输入“you said yes”。 我做错了什么?
最佳答案
您需要在@echo off
之后添加以下内容:
SETLOCAL EnableDelayedExpansion
然后,当您引用 PATH_EXISTS_ANSWER
时,不要将其包含在百分号中,而是 (%
) 将其包含在感叹号中。 (!
) 像这样:!PATH_EXISTS_ANSWER!
我测试了它,它有效。
关于windows - BAT 文件 : strange SET(? ) 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8834412/