【问题标题】:Variable not being assigned first time from input in a batch script第一次未从批处理脚本中的输入分配变量
【发布时间】:2016-08-11 01:21:05
【问题描述】:

所以我试图询问用户是否要覆盖当前的虚拟机(如果已经存在)。我已将此 .bat 文件的问题部分提取到单独的文件中以复制问题。

这个文件的代码是:

@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

这个概念是第一个如果总是返回为真(因为在这种情况下这些变量永远不会相等)并且从那里它会询问他们是否要覆盖机器。如果他们说“y”,您应该会看到“覆盖”,然后按任意键继续...

问题是它没有这样做!它似乎没有设置 machineOverwrite 变量,因此它正在进入“您没有输入 y 或 n”部分。从这里它回到起点,然后再次经历。

真正奇怪的是,下次你通过时,如果你选择“y”,它会按照它的意思做!但是,如果您选择“n”,它仍然可以使用“y”!

每次我输入任何内容时,它总是从返回 :checkOverwrite 之前获取输入,而不是最新的输入。为什么??

【问题讨论】:

标签: variables batch-file input unassigned-variable


【解决方案1】:

您的问题是,尽管尝试启用延迟扩展(使用 setlocal enabledelayedexpansion),但您实际上并没有使用它。

%var% 是正常的变量扩展,即使打开了延迟扩展。

您需要使用!var! 进行延迟变量扩展。请参阅(例如)“文档”here

【讨论】:

  • 太棒了,谢谢。我实际上已经尝试过,但错过了 % to 之一!这当然会导致问题。现已修复并支持答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 2023-04-09
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多