【问题标题】:Batch script ENDLOCAL / SET inside if statement is not working批处理脚本ENDLOCAL / SET里面if语句不起作用
【发布时间】:2013-03-19 12:23:12
【问题描述】:

我是批处理脚本的新手,我正在编写一个批处理脚本来设置环境变量。下面是我使用的批处理脚本。

if 1 == 1 (
    setlocal enableextensions enabledelayedexpansion
    SET name1=%1_hello
    endlocal & SET name=%name1%
    echo varaiable %name%
    goto :eof
)

但我面临的问题是变量name 未设置,endlocal & SET name=%name1% 中的name1 始终为空或从先前设置的环境变量中获取它。 但是没有if statement 的相同代码可以工作。

    setlocal enableextensions enabledelayedexpansion
    SET name1=%1_hello
    endlocal & SET name=%name1%
    echo varaiable %name%
    goto :eof

在上面的代码中,name1 变量被设置,name 被显示。有人可以帮我摆脱这个问题。为什么endlocal / set 与 if 语句的行为不同?

【问题讨论】:

    标签: windows batch-file command


    【解决方案1】:

    解析 IF 语句时 - 从 IF 到右括号,所有 %var% 都被这些变量的内容替换,因为它们在该行被解析时所处的位置,即在执行之前.

    【讨论】:

    • 所以使用条件 GOTO 跳过代码块,而不是条件 () 块
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多