tags:

views:

65

answers:

2

Since ERRORLEVEL is an environment variable isn't it possible that its value can be changed before I get a chance to check it in my batch file?

+2  A: 

Environment variables belong to the current "process" so they can't be changed from outside. Provided you check the error level after the relevant command in your batch file, you should be checking the right value.

You can confirm this by opening up two command windows and entering into the first:

c:> set errorlevel=7

and then the second:

c:> set errorlevel=9

then go back to the first and:

c:> echo %errorlevel%
7

You should be very careful about setting the errorlevel environment variable by the way. That particular variable is a special one in that, when you haven't set it specifically, it will automatically serve up the return code from the previous program.

Setting it explicitly overrides this behaviour, and the only way to recover is to either use if errorlevel N instead of the environment variable (it bypasses the environment variable), or use set errorlevel= to remove the override.

paxdiablo
@paxdiable: what you say about the `%errorlevel%` environment variable is true for any (env)variable you set in one cmd.exe window. It will never automagically appear in any other already opened cmd.exe window.
pipitas
Yes, that's correct. When I said errorlevel was special, that wasn't the aspect I was talking about. No env-var jumps from process to process. I was just warning against setting errorlevel specifically since it has special behaviour normally, which setting it prevents.
paxdiablo
A: 

%errorlevel% (it is not really case sensitive) is a very special environment variable. It is not at all meant for setting by users or inside batch scripts.

Also, you may run into the problem that you execute the call set errorlevel=15 but the very fact that you successfully executed the set command, may have reset the %errorlevel% you're expecting to now evaluete 0.

Should you need it

The only "legal" way to evaluate the %errorlevel% environment variable is using repeated if errorlevel statements:

if errorlevel 0 do somecommand
if errorlevel 1 do somethingelse
...
if errorlevel 255 do lastalternative

everything else is dangerous. If you indeed need to use the current %errorlevel% a few lines later, then use something like

if errorlevel 0 do set myerrorlevel=0 

and then readout %myerrorlevel%...

pipitas