I found this page (and site) very helpful for all DOS related stuff: http://www.robvanderwoude.com/errorlevel.php
- Use "IF %ERRORLEVEL% NEQ 0 SET MYERROR=1" to record whether the previous command resulted in an error code. Alternately, you can check for "IF ERRORLEVEL 1 ..." if you want to look for a specific error level.
- Be cautious of manipulations with ERRORLEVEL. It's not really an environment variable like other variables. In particular, do NOT ever use "set ERRORLEVEL=5" or similar. It will corrupt any further use of %ERRORLEVEL% syntax by fixing it at a value.
- Use "CALL FOO.BAT" instead of just "FOO.BAT" when calling subscripts. Otherwise, when that script completes it will not return to the current script.
- Use "EXIT /B 1" to return an exit code from your script. If you use "EXIT 1" it will exit the entire command shell, including closing your current window if it's running in one.
- Consider using SETLOCAL and ENDLOCAL within your script to prevent temporary environment variables from carrying through to outer shells.
Below is an example script.
:: Sample script with some error handling
SETLOCAL
SET MYPARAM=%1
if "%MYPARAM%"=="" goto :USAGE
CALL .\childscript.bat %MYPARAM%
if %ERRORLEVEL% NEQ 0 set MYERROR=1
echo.
echo Finished child script. Handling errors now...
if %MYERROR%==1 GOTO :ERROR
echo It worked!
ENDLOCAL
set SOME_EXTERNAL_VARIABLE=1
GOTO :EOF
:USAGE
echo Please provide a command line parameter.
EXIT /B 2
:ERROR
echo It didn't work, dude.
EXIT /B 1
Update: I was wrong about the ERRORLEVEL syntax earlier, so I updated after some testing.
No comments:
Post a Comment