Consider the following bat, test.bat (PC01 is off):
mkdir \\PC01\\c$\Test || goto :eof
If I run that bat from a command shell:
> test.bat || echo 99
> if ERRORLEVEL 1 echo 55
The output is just 55. No 99. There is an errorlevel, but the ||
operator did not see it.
If I run that bat using cmd /c -
> cmd /c test.bat || echo 99
> if ERRORLEVEL 1 echo 55
The output is blank. Errorlevel is 0.
If I remove the || goto :eof
, everything works as one would predict — i.e the output would be
99 55
Does anyone know why this half-baked semi-existent ERRORLEVEL behaviour is occurring?
In most circumstances,
||
is the most reliable way to detect an error. But you have stumbled on one of the rare cases where ERRORLEVEL works but||
does not.The problem stems from the fact that your error is raised within a batch script, and
||
responds to the return code of the most recently executed command. You are thinking of test.bat as a single "command", but actually it is a sequence of commands. The last command executed within the script isGOTO :EOF
, and that executed successfully. So yourtest.bat||echo 99
is responding to the success of theGOTO :EOF
.When you remove the
||GOTO :EOF
from within the script, then yourtest.bat||echo99
sees the result of the failedmkdir
. But if you were to add aREM
command to the end of test.bat, thentest.bat||echo 99
would respond to the success of theREM
, and the error would be masked again.The ERRORLEVEL is still non-zero after
test.bat||echo 99
because commands likeGOTO
andREM
do not clear any prior non-zero ERRORLEVEL upon success. This is one of many pieces of evidence that ERRORLEVEL and the return code are not quite the same thing. It definitely gets confusing.You can treat test.bat as a unit command and get the behavior you want by using CALL.
This works because the
CALL
command temporarily transfers control to the called script. When the script terminates, control is returned to theCALL
command, and it returns the current ERRORLEVEL. So||echo 99
is responding to the error returned by the CALL command itself, not the last command within the script.Now for the
CMD /C
issue.The return code returned by
CMD /C
is the return code of the last command executed.This works:
because
CMD /C
returns the ERRORLEVEL returned by theCALL
statementBut this fails entirely:
Without the
CALL
, theCMD /C
returns the return code of the last executed command, which is theGOTO :EOF
. TheCMD /C
also sets the ERRORLEVEL to the same return code, so now there is no evidence that there ever was an error within the script.And down the rabbit hole we go
R.L.H., in his answer and in his comments to my answer, is concerned that
||
sometimes clears the ERRORLEVEL. He provides evidence that appears to back up his conclusion. But the situation isn't that simple, and it turns out that||
is the most reliable (but still not perfect) way to detect errors.As I stated earlier, the return code that all external commands return upon exit is not the same thing as the cmd.exe ERRORLEVEL.
The ERRORLEVEL is a state maintained within the cmd.exe session itself, wholly distinct from return codes.
This is even documented in the definition of the exitCode within the EXIT help
(
help exit
orexit /?
)When an external command is run by CMD.EXE, it detects the executeable's return code and sets the ERRORLEVEL to match. Note that it is only a convention that 0 means success, and non-zero means error. Some external commands may not follow that convention. For example, the HELP command (help.exe) does not follow the convention - it returns 0 if you specify an invalid command as in
help bogus
, but returns 1 if you ask for help on a valid command, as inhelp rem
.The
||
operator never clears the ERRORLEVEL when an external command is executed. The process exit code is detected and fires||
if it is non-zero, and the ERRORLEVEL will still match the exit code. That being said, the commands that appear after&&
and/or||
may modify the ERRORLEVEL, so one has to be careful.But there are many other situations besides external commands where we developers care about success/failure and return codes/ERRORLEVELs.
<
,>
, and>>
Unfortunately, CMD.EXE is not at all consistent in how it handles error conditions for these situations. CMD.EXE has multiple internal points where it must detect errors, presumably through some form of internal return code that is not necessarily the ERRORLEVEL, and at each of these points CMD.EXE is in a position to set the ERRORLEVEL depending on what it finds.
For my test cases below, note that
(call )
, with a space, is arcane syntax that clears the ERRORLEVEL to 0 before each test. Later on, I will also use(call)
, without a space, to set the ERRORLEVEL to 1Also note that delayed expansion has been enabled within my command session by using
cmd /v: on
prior to running my testsThe vast majority of internal commands set the ERRORLEVEL to a non-zero value upon failure, and the error condition also fires
||
. The||
never clears or modifies the ERRORLEVEL in these cases. Here are a couple examples:Then there is at least one command, RD, (possibly more), as well as the redirection operators that fire
||
upon error, but do not set ERRORLEVEL unless||
is used.See "rd" exits with errorlevel set to 0 on error when deletion fails, etc and File redirection in Windows and %errorlevel% for more information.
I know of one internal command (there may be others) plus basic failed I/O operations that can issue error messages to stderr, yet they don't fire
||
nor do they set a non-zero ERRORLEVEL.The DEL command can print an error if the file is read only, or does not exist, but it does not fire
||
or set ERRORLEVEL to non-zeroSee https://stackoverflow.com/a/32068760/1012053 for a bit more information related to DEL errors.
In much the same way, when stdout has been successfully redirected to a file on a USB device, but then the device is removed before a command such as ECHO tries to write to the device, then the ECHO will fail with an error message to stderr, yet
||
does not fire, and ERRORLEVEL is not set to non-zero. See http://www.dostips.com/forum/viewtopic.php?f=3&t=6881 for more info.Then we have the case where a batch script is executed - the actual subject of the OP's question. Without
CALL
, The||
operator responds to the last command executed within the script. WithCALL
, the||
operator responds to the value returned by theCALL
command, which is the final ERRORLEVEL that exists upon batch termination.Finally, we have the case that R.L.H. reports, where an invalid command is reported as ERRORLEVEL 9009 normally, but as ERRORLEVEL 1 if
||
is used.I can't prove this, but I suspect that the detection of command failure and setting of ERRORLEVEL to 9009 occurs very late in the command execution process. I'm guessing that
||
intercepts the error detection before the 9009 is set, at which point it sets it to 1 instead. So I don't think||
is clearing the 9009 error, but rather it is an alternate pathway by which the error is handled and set.An alternate mechanism for this behavior is that the invalid command could always set the ERRORLEVEL to 9009, yet have a different return code of 1. The
||
could subsequently detect the 1 return code and set the ERRORLEVEL to match, thus overwriting the 9009.Regardless, I am not aware of any other situation where a non-zero ERRORLEVEL result is different depending on whether
||
was used or not.So that takes care of what happens when a command fails. But what about when an internal command succeeds? Unfortunately, CMD.EXE is even less consistent than it was with errors. It varies by command, and may also depend on whether it is executed from the command prompt, from a batch script with a
.bat
extension, or from a batch script with a.cmd
extension.I am basing all of the discussion below on Windows 10 behavior. I doubt there are differences with earlier Windows versions that use cmd.exe, but it is possible.
The following commands always clear the ERRORLEVEL to 0 upon success, regardless of context:
Example:
call echo OK
The next set of commands never clear the ERRORLEVEL to 0 upon success, regardless of context, but instead preserve any existing non-zero value ERRORLEVEL:
EXIT /B 0
clears the ERRORLEVEL, butEXIT /B
without value preserves the prior ERRORLEVEL.And then there are these commands that do not clear ERRORLEVEL upon success if issued from the command line or within a script with a
.bat
extension, but do clear the ERRORLEVEL to 0 if issued from a script with a.cmd
extension. See https://stackoverflow.com/a/148991/1012053 and https://groups.google.com/forum/#!msg/microsoft.public.win2000.cmdprompt.admin/XHeUq8oe2wk/LIEViGNmkK0J for more info.Regardless of any ERRORLEVEL value, the
&&
operator detects if the prior command was successful, and only executes the subsequent command(s) if it was. The&&
operator ignores the value of ERRORLEVEL, and never modifies it.Here are two examples that show that
&&
always fires if the prior command was successful, even if the ERRORLEVEL is non-zero. The CD command is an example where the command clears any prior ERRORLEVEL, and the ECHO command is an example where the command does not clear the prior ERRORLEVEL. Note, I am using(call)
to force ERRORLEVEL to 1 before issuing the command that succeeds.In all of my code examples for error detection, I was relying on the fact that ECHO never clears a previously existing non-zero ERRORLEVEL. But the script below is an example of what can happen when other commands are used after
&&
or||
.Here is the output when the script has a
.bat
extension:And here is the output when the script has a
.cmd
extension:Remember that every executed command has the potential to alter the ERRORLEVEL. So even though
&&
and||
are the most reliable ways to detect command success or failure, one must be careful about what commands are used after those operators if you care about the ERRORLEVEL value.And now it is time to climb out of this stinking rabbit hole and get some fresh air!
So what have we learned?
There is no single perfect method to detect whether any arbitrary command was successful or failed. However,
&&
and||
are the most reliable methods to detect success and failure.In general, neither
&&
nor||
modify the ERRORLEVEL directly. But there are a few rare exceptions.||
properly sets the ERRORLEVEL that would otherwise be missed when RD or redirection fails||
sets a different ERRORLEVEL upon failed execution of an invalid command then would occur if||
were not used (1 vs. 9009).Finally,
||
does not detect a non-zero ERRORLEVEL returned by a batch script as an error unless the CALL command was used.If you rely strictly on
if errorlevel 1 ...
orif %errorlevel% neq 0 ...
to detect errors, then you run the risk of missing errors that RD and redirection (and others?) might throw, and you also run the risk of mistakenly thinking certain internal commands failed when in reality it could be a holdover from a prior command that failed.The true Errorlevel doesn't survive the double pipe (on failure) operator.
Use logic instead. For example, below is one way you could do it:
edit:
If the command that precedes this is not a single command then more has to be done to track errorlevel. Example if you call a script, then in that script you have to manage the passing of errorlevel back to this code.
edit 2:
Here are test scenarios where the ERRORLEVEL should be '9009' and their output.
1) No failure piping, uses if logic.
2) Failure piping, echo
3) Failure piping, goto
So if all you care about is "Something" failed, then OK. Code 1 is as good as anything else. But if you need to know "what" failed, then you can't just failure pipe and let it wipe out the actual result.
To build a solution for batch files to set the return code while using
goto :eof
you can change your script a bit.Now you can use
The only drawback here is the loss of the errorlevel.
In this case the return code is set to
false
but the errorlevel is always set to1
, by the invalid(call)
Currently I can't found any possible way to set both, the errorlevel and the return code to user defined values