Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success? - batch-file

A frequent method to handling errors within Windows batch scripts is to use things like
if errorlevel 1 ... or if %errorlevel% neq 0 .... Often times one wants the error handling code to preserve the ERRORLEVEL.
I believe all external commands will always result in ERRORLEVEL being set to some value, so the error handling code must preserve the ERRORLEVEL in an environment variable prior to executing an external command.
But what about internal commands? The problem is, some internal commands clear the ERRORLEVEL to 0 when they succeed, and some do not. And I can't find any documentation specifying which commands do what.
So the question is, which internal commands clear the ERRORLEVEL to 0 upon success? This is not a general question about returned ERRORLEVEL codes, but strictly about success results.
There are posts like What is the easiest way to reset ERRORLEVEL to zero? and Windows batch files: .bat vs .cmd? that give partial answers. But I have never seen a comprehensive list.
Note: I've been curious about this for years. So I finally decided to run a bunch of experiments and come up with a definitive answer. I'm posting this Q&A to share what I have found.

This answer is based on experiments I ran under Windows 10. I doubt there are differences with earlier Windows versions that use cmd.exe, but it is possible.
Also note - This answer does not attempt to document the ERRORLEVEL result when an internal command encounters an error (except for a wee bit concerning DEL and ERASE)
Not only are there difference between commands, but a single command can behave differently depending on whether it was run from the command line, or within a batch script with a .bat extension, or from within a batch script with a .cmd extension.
The following set of commands never clear the ERRORLEVEL to 0 upon success, regardless of context, but instead preserve the prior ERRORLEVEL:
BREAK
CLS
ECHO
ENDLOCAL
FOR : Obviously, commands in the DO clause may set the ERRORLEVEL, but a successful FOR with at least one iteration does not set the ERRORLEVEL to 0 on its own.
GOTO
IF : Obviously, commands executed by IF may set the ERRORLEVEL, but a successful IF does not set ERRORLEVEL to 0 on its own.
KEYS
PAUSE
POPD
RD
REM
RMDIR
SHIFT
START
TITLE
The next set of commands always clear the ERRORLEVEL to 0 upon success, regardless of context:
CD
CHDIR
COLOR
COPY
DATE
DEL : Always clears ERRORLEVEL, even if the DEL fails (except when run without any file argument).
DIR
ERASE : Always clears ERRORLEVEL, even if ERASE fails. (except when run without any file argument).
MD
MKDIR
MKLINK
MOVE
PUSHD
REN
RENAME
SETLOCAL
TIME
TYPE
VER
VERIFY
VOL
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.
ASSOC
DPATH
FTYPE
PATH
PROMPT
SET
Lastly, there are these commands that do not fit neatly into any of the prior categories:
CALL : If a :routine or batch script is CALLed, then ERRORLEVEL is exclusively controlled by the CALLed script or :routine. But any other type of successful CALL to a command will always clear ERRORLEVEL to 0 if the CALLed command does not otherwise set it.
Example: call echo OK.
EXIT : If used without /B, then the cmd.exe session terminates and there is no more ERRORLEVEL, just the cmd.exe return code. Obviously EXIT /B 0 clears the ERRORLEVEL to 0, but EXIT /B without a value preserves the prior ERRORLEVEL.
I believe that accounts for all internal commands, unless there is an undocumented command that I missed.

Your description of CALL command is incomplete:
CALL : Clears ERRORLEVEL if the CALLed command does not otherwise set it.
Example: call echo OK.
Check this small example:
#echo off
call :setTwo
echo Set two: %errorlevel%
call :preserve
echo Preserve: %errorlevel%
call echo Reset
echo Reset: %errorlevel%
call :subNotExists 2> NUL
echo Sub not exist: %errorlevel%
goto :EOF
:setTwo
exit /B 2
:preserve
echo Preserve
exit /B
Output:
Set two: 2
Preserve
Preserve: 2
Reset
Reset: 0
Sub not exist: 1
CALL description should say something like this:
CALL : Clears ERRORLEVEL if the CALLed command does not otherwise set it. Example: call echo OK, but if the called command is a subroutine it preserves the prior ERRORLEVEL. If the called subroutine does not exist, it sets the ERRORLEVEL to 1.

Related

Is Windows %ERRORLEVEL% == $? in Linux

Trying my hands on windows batch files, in the below code that I found by searching in www.
#ECHO OFF
REM Call this with two arguments, and it will add them.
SET a=%1+%2
IF %ERRORLEVEL%==0 (goto errors-0) ELSE (goto errors-1)
REM Instead of using goto with the variable, this uses an IF-ELSE structure
:errors-0
REM This is if it was successful
ECHO %a%
goto exit
:errors-1
REM this is if it had an error:
ECHO Errors occurred.
goto exit
REM GUESS WHAT, THIS REM WILL NEVER EVER BE READ! IT WILL BE SKIPPED OVER BY THE GOTOS
:exit
ECHO.
ECHO press any key to exit.
PAUSE>nul
The code is suppose to take 2 arguments, add them and echo the result.
But this won't execute with success on my Windows 8.1 machine. Below is what I get:
C:\ProjectDoc>add3.bat
Errors occurred.
press any key to exit.
So, U added an echo for the ERRORLEVEL to see its value after executing the command SET. Below is the output:
C:\ProjectDoc>add3.bat 2 3
9009
Errors occurred.
press any key to exit.
C:\ProjectDoc>
So, is this errorlevel in Windows equal to the $? of Linux. Should it be returning 0 for every successful execution of a command or is it different? Reading some docs relates it to the Linux $? but it isn't clearly working as $? in Linux.
Yes, to be precise, %errorlevel% is analogous to $? in Bash shell.
In your batch file, SET a=%1+%2 is not doing what you expect it to do. It just sets the value of the variable a to the string "2+3" assuming you ran the file with arguments 2 3. If you want to do arithmetic you need to use the /A option: set /a a=%1+%2.
The SET command (and many other built-in commands) only set the ERRORLEVEL if there has actually been an error. If it was successful, the ERRORLEVEL will retain its previous value. I think this is what you're witnessing in your question.
By contrast, when a command runs an executable file, when the process completes it always sets the ERRORLEVEL.
As well as checking the ERRORLEVEL variable for specific values, it is idiomatic (for historical reasons) to check the errorlevel using the following expression
IF ERRORLEVEL 1 ECHO Hello
This will run the given command if ERRORLEVEL is 1 or above - in other words, if any error has occurred.

Compare text from two files and do something if they are diffrent

So I need to compare two text files and if there is a difference in content in one of them then tell the batch file to GOTO Diffrence I know that the FC command can check diffrences but can I use it to make it goto a diffrent place
so I run
fc %cd%\ActiveVer.txt %cd%\currentver.txt
ActiveVer.txt says:
0.5.6
and currentver.txt says:
0.5.7
fc tells me the difference.
But I'm trying to see and make it run GOTO out-of-date if there is a difference and do echo You are up to date! if there is none.
Should I run another command to do this or is there something that allows me to do that with fc?
Most commands return an error code upon completion. By convention, zero equates to success, and non-zero equates to failure (this is a general rule - there are exceptions). So most of this answer can be applied to any command, as long as you know how to interpret the returned error code.
The FC command returns 0 if the files match, and 1 it there is at least one difference. You don't need to see the output of the command (the differences), so you can redirect stdout to nul.
One option is to use IF ERRORLEVEL N, which evaluates to true if the returned error code is >= N.
fc ActiveVer.txt CurrentVer.txt >nul
if errorlevel 1 goto outOfDate
echo you are Up-To-Date
exit /b
:outOfDate
echo you are Out-Of-Date
exit /b
Note that %cd%\file and file are equivalent - the %cd% is not needed.
Another option is to check for a specific value by using the dynamic %ERRORLEVEL% "variable".
fc ActiveVer.txt CurrentVer.txt >nul
if %errorlevel%==1 goto outOfDate
echo you are Up-To-Date
exit /b
:outOfDate
echo you are Out-Of-Date
exit /b
But I almost never use either syntax above. Instead I use the conditional command concatenation operators && and ||. Commands after && only execute if the prior command returned zero, and commands after || execute if the command returned non-zero. Note that commands after && might fail, which could cause the || commands to fire, even if the original command succeeded. For this reason, it is a good idea to end your && commands with a command that is guaranteed to succeed. A good choice is (call ), which does nothing other than return 0 (success).
someCommand && (
REM Success commands go here
REM Make sure the last commmand in this block returns 0
(call )
) || (
REM Error commands go here
)
You simply want to GOTO if FC "fails" (finds a difference), so you only need the ||.
fc ActiveVer.txt CurrentVer.txt >nul || goto outOfDate
echo You are Up-To-Date
exit /b
:outOfDate
echo You are Out-Of-Date

How to prevent MSBuild from aborting on signtool errorlevel <> 0

In our current setup build process (WiX 3.9), certain files get digitally signed. To avoid signing an unchange file again, I want to check each file for a signature and skip signing if it's already signed.
I've tried using signtool.exe verify /pa filename.exe to check if the file is already signed, and signtool returns with a nonzero ERRORLEVEL if there is no signature. I thought I could check the error code after the call and handle it appropriately:
signtool.exe verify /pa %1
IF ERRORLEVEL 0 goto already_signed
rem Sign file now
[...]
goto finished
:already_signed
echo File %1 is already signed, skipping
:finished
This works fine if a signature is found and signtool returns 0. But if no signature is found, resulting in a nonzero ERRORLEVEL, MSBuild takes immediate notice of that and displays an error message: EXEC : SignTool error : No signature found. One step later, the build fails due to a -1 return code from the signing batch file. In terms of the build process however, there were no errors that would have to be treated like ones.
I've already tried to reset the ERRORLEVEL to 0 after the signtool verify call, but that doesn't work. Any ideas?
As S.T. suggests above, simply add exit /b 0 below your :finished label. If you want to reset %ERRORLEVEL% without exiting your script, you can do cmd /c exit /b 0, then %ERRORLEVEL% will be reset to zero and your script will continue.
Just so I feel like I put some effort into this answer, I'll offer an unrelated tip. :)
Another neat trick for testing exit code status is conditional execution.
>NUL 2>&1 signtool.exe verify /pa "%~1" && (
echo File %1 is already signed, skipping
) || (
rem Sign file now
[...]
exit /b 0
)
The >NUL 2>&1 stuff simply hides all stdout and stderr output of signtool.exe. The code block after && fires if signtool exits 0. Otherwise, the code block after || fires.

Is ERRORLEVEL reliable?

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?
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(a) instead of the environment variable (it bypasses the environment variable), or use set errorlevel= to remove the override.
(a) The correct way to do this is mandated by fact that the errorlevel expression is true if the error level is greater than or equal to the value specified. Because of that, you should do it in reverse order, something like:
if errorlevel 3 goto :got3ormore
if errorlevel 2 goto :got2
if errorlevel 1 goto :got1
if errorlevel 0 goto :got0
goto :gotnegative
%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%...

Can a batch file capture the exit codes of the commands it is invoking?

Basically, let's say that I have a batch file that calls myapp1.exe and myapp1.exe exits with Exit Code 1. Can the batch file capture this information and either force the batch file to exit with that same exit code or perform some other logic?
#echo off
rem ...
set errorlevel=
MyApp1.exe
exit /b %errorlevel%
would be the explicit variant.
The accepted answer is correct, but if you are using call to call another batch script, and that second batch script is using SetLocal, you may need to use a parsing trick to accomplish this. If you are running into this, add the following code before your exit b:
ENDLOCAL&set myvariable=%myvariable%
Now the value of myvariable is made available to the calling context and you can see the value in the other script.
References:
https://stackoverflow.com/a/16167938/89590
http://www.borngeek.com/2008/05/22/exiting-batch-file-contexts/
You could try using errorlevels. Some more info here.
%ERRORLEVEL% stores the return value of last executed command
call program.exe
echo program.exe returns "%ERRORLEVEL%"
IF %ERRORLEVEL% NEQ 0 (
echo FAILED
)

Resources