batch file test error level
I'm trying to conditionally run an exe from a batch file conditionally upon another exe executing successfully.
I've tried a few dif开发者_开发百科ferent combinations of IF and ERRORLEVEL but none seem to work
"..\..\..\TeamBuildTypes\Current Branch\DatabaseUpdate.exe" -s localhost\sql2008r2
IF %ERRORLEVEL% 1(
"..\..\..\TeamBuildTypes\Current Branch\DatabaseUpdate.exe" -s localhost\sql2008
)
Pause
Gives me the error
1( was unexpected at this time.
Where am I going wrong here?
IF ERRORLEVEL ...
is a special syntax supported since the DOS days, the %ERRORLEVEL%
variable support was added in WinNT.
The original syntax is used like this:
call someapp.exe
if errorlevel 1 goto handleerror1orhigher
echo succuess...
To use the variable, use the normal IF syntax: if %errorlevel%==0 echo success...
Note that %errorlevel%
stops working if someone does set errorlevel=foo
and it might not get updated for internal cmd.exe commands.
An alternative solution is to use &&
:
call someapp.exe && (echo success) || (echo error!)
There are (at least) two known cases where errorlevel is broken and you must use ||
instead:
RD
/RMDir
>
file redirection
Negative errorlevels can create problem. Try something like this:
IF '%ERRORLEVEL%'=='0' GOTO OK
Never use parenthesis to enclose any variables. Parentheses are a block construct that will break DO and IF blocks and other things. Instead use safe plain characters like "X" to enclose variables E.g. To test for ERRORLEVEL of ONLY 0 use ... IF X%ERRORLEVEL%X == X0X Echo or GOTO etc ... It is safer this way as many special characters have special meanings and will break more complex code without any warning and take hours to debug. I know, this trap has befallen me whenever I forget my own advice.
精彩评论