0

How can dos batch subscripts change a var initially defined in a calling script? For example, this script is failing to increment the VAR variable, as expected. This is something like a 'global variable' that I am trying to use.

one.bat

@echo off
ENDLOCAL
SET /A GLOBALVAR=0
cmd.exe /C two.bat
ECHO ERRORLEVEL after cmd.exe : %ERRORLEVEL%
CALL two.bat
ECHO ERRORLEVEL after CALL : %ERRORLEVEL%
ECHO GLOBALVAR=%GLOBALVAR%
pause

two.bat

@ECHO off
:: error if GLOBALVAR variable not detected
IF NOT DEFINED GLOBALVAR EXIT /B 9
SET /A GLOBALVAR=%GLOBALVAR%+1
EXIT /B 0

And the output:

ERRORLEVEL after cmd.exe : 0
ERRORLEVEL after CALL : 0
GLOBALVAR=1
Press any key to continue . . .
4

1 回答 1

2

而不是使用 " cmd.exe /c two.bat" 你应该使用 " call two.bat" 就像你稍后做两行一样。这two.bat在调用者环境的上下文中执行,因此two.bat可以访问变量GLOBALVAR

在第 3 行two.bat,写“ GLOBALVAR”而不是“ VAR”。这个错字(?)导致two.bat提前退出而不改变GLOBALVAR.

于 2013-06-24T19:45:13.943 回答