if 语句内的批处理脚本 ENDLOCAL / SET 不起作用

问题描述 投票:0回答:1

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

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

但我面临的问题是变量

name
未设置,并且
name1
中的
endlocal & SET name=%name1%
始终为 null 或从之前设置的环境变量中获取它。 但是没有
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个回答
3
投票

当解析 IF 语句时 - 从

IF
到其右括号,所有
%var%
都将替换为这些变量在解析该行时(即执行之前)的内容。

© www.soinside.com 2019 - 2024. All rights reserved.