0

我正在使用全局变量来存储批处理“函数”的返回值。它以奇怪的方式变化:

result local = 1
result global = 1
result = 4

因此,函数调用后,结果以某种方式变回 4。这里有什么问题?

set result=4

if %build%==1 (
    call :build_1
    echo "result=%result%"
    if %result%==4 (
        exit /b 4
        goto error
    )
    call :build_2
    if %result%==4 (
        exit /b 4
        goto error
    )
    call :build_3
    if %result%==4 (
        exit /b 4
        goto error
    )
    call :build_4
    if %result%==4 (
        exit /b 4
        goto error
    )
    goto success
)


rem return error/success code in result variable
:build_1
    setlocal

    rem Stage 1

    call    :build_one_unit
    if %errorlevel%==4 (
        echo FAILED!
        set result=4
        exit /b
    )

    rem Stage 2

    call    :build_one_unit
    if %errorlevel%==4 (
        echo FAILED!
        set result=4
        exit /b
    )

    set result=1
    echo "result local = %result%"
    endlocal & set result=%result%
    echo "result global = %result%"

goto:eof
4

1 回答 1

3

你的if %build%==1 ( ...... ),是的,从左括号到右括号,被读取并解释为一个块。发生这种情况时,结果变量的值为 4。解释块时,所有变量都将替换为它们的值。不是在执行到达带有 的行时if %result%==4,而是在处理初始 if 时。

您需要的称为延迟变量扩展。它允许您使用带有 !var! 的变量!(而不是 %var%)表示法,告诉 cmd 需要在访问时检查/替换此变量,而不是在解释块时。您的代码应为:

setlocal enabledelayedexpansion

set return=4

if %build%==1 (
    call :build_1
    echo "result=!result!"
    if !result!==4 (
        exit /b 4
        goto error
    )
    ....
    ....
)
于 2013-10-31T10:59:27.790 回答