Wednesday, October 5, 2011

Common DOS batch file error handling mistakes I make

I write a decent amount of batch scripts now days to automate things on windows server boxes. Unfortunately, I don't do it quite frequently enough to remember all the crazy syntax of DOS commands. One of these errors is error handling. These are the things I commonly need to deal with.

I found this page (and site) very helpful for all DOS related stuff: http://www.robvanderwoude.com/errorlevel.php

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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