Came across a definite gotcha today in batch file programming, when I noticed that we had SET ERRORLEVEL=0 in one of our batch files. Turns out that once you set this variable explicitly then any command you run after will not be able to change the value of the %ERRORLEVEL% variable. E.G.
(note SET ERRORLEVEL=0 does not do what youthink, if you're using IF ERRORLEVEL 1 goto MYLABEL type syntax).
C:\>dir AUTOEXEC.BAT
Volume in drive C has no label.
Volume Serial Number is 907A-1111
Directory of C:\
02/08/2006 09:58 0 AUTOEXEC.BAT
1 File(s) 0 bytes
0 Dir(s) 11,104,747,520 bytes free
C:\>echo %errorlevel%
0
C:\>dir lkksjdfljsdk
Volume in drive C has no label.
Volume Serial Number is 907A-1111
Directory of C:\
File Not Found
C:\>echo %errorlevel%
1
C:\>set errorlevel=0
Now you would expect the next rogue dir statement to set the errorlevel back to 1
C:\>dir lkksjdfljsdk
Volume in drive C has no label.
Volume Serial Number is 907A-1111
Directory of C:\
File Not Found
But as you can see it does not
C:\>echo %errorlevel%
0
A neat way to reset the error level is to just use the verify >nul command, as this works fine
C:\>dir sdkfljs
Volume in drive C has no label.
Volume Serial Number is 907A-1111
Directory of C:\
File Not Found
C:\>echo %errorlevel%
1
C:\>verify >nul
C:\>echo %errorlevel%
0
C:\>dir lskjlkj
Volume in drive C has no label.
Volume Serial Number is 907A-1111
Directory of C:\
File Not Found
C:\>echo %errorlevel%
1
C:\>
I have since had the following reply stating that the above logic could be a little misleading...
I just stumbled over your blog post on the mentioned subject and since comments are disabled I point this out via e-mail. What you were doing there is a common fallacy but no less wrong. The "Errorlevel" status is not maintained by the shell in an environment variable. The *pseudo-variable* %ERRORLEVEL% is merely a convenience thing to avoid typing things such as
if errorlevel 1 echo Error
The pseudo-variable can be overwritten by a real environment variable with the same name but this has absolutely no effect on the error level. What you saw when executing
echo %errorlevel%
was merely the content of the variable you created earlier.
c:\>set errorlevel=0
c:\>dir seukhsuhks
[...] (dir not found)
c:\>if errorlevel 1 echo Error
Error
c:\>echo %errorlevel%
0
This actually works as expected. The concept of "error level" and the variable are two distinct things now that the pseudo-variable got overshadowed by an actual variable with the same name.
Helpful read on this matter is also Raymond Chen's article on the subject:
http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx
Regards,
Johannes