What I mean is, don't ever have an environment variable named errorlevel. That's just a bad idea. Windows command processor will take your definition every time. This means if you set your errorlevel, subsequent check for any command's errorlevel will not work.
set errorlevel=0
call some_command_that_returns_non_zero.cmd
if "%errorlevel%" EQU "0" (
echo SUCCESS
) else (
echo FAIL
)
You will always get errorlevel set to 0 or whatever value you happen to have it set to. So the check in the above snippet will always return success.
Well, OK, I admit. When I said above that your subsequent errorlevel check will not work, I lied. The other way of checking errorlevel will still work.
set errorlevel=0
call some_command_that_returns_non_zero.cmd
if errorlevel 1 (
echo FAIL
) else (
echo SUCCESS
)
That would still work. But just save yourself some trouble and stay away from it.
5 comments:
Thanks for spreading the word about setting errorlevels. That was a source of some of my difficulties.
I know this is an old post, but I found it from another site talking about the errorlevel.
I discovered that the following bit of code won't work like you really want it to:
some code that fails and sets errorlevel to 1
if errorlevel == 0 (
do success code
) else (
do some other code that would normally set errorlevel to 0
if errorlevel neq 0 (
do fail code
)
)
What happens in the second if statement, the errorlevel is always 1.
Machtyn,
Your snippet is missing the % for the errorlevel. To use it the way you use it in your snippet, you need to do it like:
if %errorlevel% == 0
...
if %errorlevel% neq 0
But assuming you just made a typo in your snippet, the likely cause is that you did not set delayed expansion. Since the command that sets errorlevel to 0 is inside an else() block, you need to use ! to access the real errorlevel value.
...
) else (
do some code that sets errorlevel to 0
if !errorlevel! neq 0 (
do fail code
)
)
Please see mhy other post about delayed expansion for some more info.
I got burned many times for checking errer levels by using == in an if statement eg.
1. if %errorlevel%==0
2. if errorlevel==0
I've since found that the best method that always works for me is to capture the errorlevel with a statement like:
IF NOT ERRORLEVEL 0 set MyErr=%ERRORLEVEL%
and then to continue processing with the MyErr variable!
Because of reverse order of revealing ERRORLEVEL, ERRORLEVEL 0 is always true, even in case of ERRORLEVEL 1 or higher. So "IF NOT ERRORLEVEL 0" is NEVER true. For what I can understand.
Post a Comment