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.
3 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.
Post a Comment