Is Windows %ERRORLEVEL% == $? in Linux - batch-file

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.

Related

batch choice command will not work

I have this question about why this choice command won't work. I've looked on this site and compared all my scripting and I just can't figure out why it won't work
http://www.computerhope.com/issues/ch001674.htm
#ECHO OFF
:START
echo 1 to quit or 2 to print hello and go back to this screen
CHOICE /C:12 /N
IF ERRORLEVEL ==1 GOTO QUIT
IF ERRORLEVEL ==2 GOTO HELLO
GOTO :START
:QUIT
EXIT
:HELLO
ECHO hello
GOTO :END
:END
I've made a couple of changes and removed unnecessary code.
#ECHO OFF
:START
CLS
ECHO=1 to quit or 2 to print hello and go back to this screen
CHOICE /C 12 /N
IF ERRORLEVEL 2 (CALL :HELLO & GOTO START)
EXIT /B
:HELLO
ECHO=hello
TIMEOUT 2 1>NUL
Simpler:
#ECHO OFF
:START
echo 1 to quit or 2 to print hello and go back to this screen
CHOICE /C 12 /N
GOTO OPTION-%ERRORLEVEL%
:OPTION-1 Quit
EXIT
:OPTION-2 Hello
ECHO hello
GOTO START
Testing on the errorlevel is done wrong.
There are two possibilities:
#ECHO OFF
:BEGIN
ECHO 1 to quit or 2 to print hello and go back to this screen
CHOICE /C:12 /N
IF ERRORLEVEL 2 GOTO HELLO
IF ERRORLEVEL 1 EXIT /B
GOTO BEGIN
:HELLO
ECHO hello
GOTO BEGIN
For full details see the chapter about CHOICE in my answer on: How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
The batch user must press either 1 or 2 as otherwise the batch execution is not continued. So testing for the exit code can be done from highest to lowest with:
if errorlevel X ...
That means IF the exit code assigned to the dynamic variable errorlevel is greater OR equal X THEN execute the command (or command block).
The advantage of using this syntax is that it even works in a command block without the need to use delayed variable expansion.
The second possibility is:
#ECHO OFF
:BEGIN
ECHO 1 to quit or 2 to print hello and go back to this screen
CHOICE /C:12 /N
IF %ERRORLEVEL% == 1 EXIT /B
IF %ERRORLEVEL% == 2 GOTO HELLO
GOTO BEGIN
:HELLO
ECHO hello
GOTO BEGIN
By explicitly referencing the dynamic variable ERRORLEVEL, here with expansion before IF evaluates the condition, the order of the errorlevel checks does not matter anymore.
The disadvantage of this method is the need of using delayed expansion if CHOICE and the errorlevel evaluating conditions are within a command block defined with ( ... ).
Run in a command prompt window if /? and set /? for help about right usage of the commands IF and SET respectively get information about delayed variable expansion.
It is possible to use START as label, but it is not advisable to do so because of START is an internal command of Windows command processor. You get troubles on finding START meaning the label and START meaning the command when your batch file will use ever also the command START. BEGIN is used as label for that reason.
It is also advisable to use command EXIT always with parameter /B at least during developing a batch file to exit only the batch processing, but do not completely exit the running command process independent on calling hierarchy and option used on starting cmd.exe.
It is much easier to debug a batch file by running it from within a command prompt window (cmd.exe started with option /K to keep console window open) instead of double clicking on the batch file (cmd.exe started with option /C to close on batch execution finished) on using exit /B instead of just exit as the command prompt window keeps open. Run in a command prompt window cmd /? for details about the options of the Windows Command Processor.
GOTO BEGIN after the two errorlevel evaluations is only executed on user pressing Ctrl+C or Ctrl+Break on this prompt and presses on prompt output by cmd to terminate the batch job the key N. That results in an exit of CHOICE with exit code 0.
It would be better to use %SystemRoot%\System32\choice.exe instead of just CHOICE if the batch file is for Windows Vista or Windows Server 2003 or newer Windows versions with support of Windows command CHOICE.

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

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.

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 can I display a description based on errorlevel value?

I'm writing a batch script to install an exe and a successful installation returns 0 and other codes mean different reasons.
I know I can print those error code(s) by echo %errorlevel%
Can I print the description related to the code instead? If so, how?
i.e. print 'successful' for code 0, etc.
Add below lines to print a message using error codes
if %errorlevel% equ 0 echo Successful
if %errorlevel% NEQ 0 echo Not Successful
Because errorlevel 0 indicates that return values of last executed command is successful,other return values have their own meaning
You can use || to act on failure, for simplicities sake this should do fine.
if %errorlevel% equ 0 echo Installed! || echo Install failed...
And && to activate on success.
del file.ext && echo File deleted.
The reason I don't provide a per errorlevel basis is that there can be up to 255 of them, something that would take an exceedingly high amount of time, and is further hindered by the tendency of programs not publically showing or ever documenting what each and every errorlevel means.
Something good to keep in mind is the difference between %errorlevel% and errorlevel. here

Batch File conditional statement not working correctly

So i am attempting to make a simple script to check if an application is running using a external text file (using 1 and 0 for if running or is not). However i cannot seem to get the statement working correctly..
setlocal enabledelayedexpansion
set /p Running=<IsRunning.txt
IF %Running% EQU 0(GOTO ProgramNotRunning)
IF %Running% EQU 1(GOTO ProgramRunning)
:ProgramNotRunning
echo program starting
echo 0 >IsRunning.txt
echo 1 >IsRunning.txt
GOTO:EOF
:ProgramRunning
echo program already running
GOTO:EOF
The issue is no matter what value it is, it always only ever runs the ProgramNotRunning code block and not the other.
Prior to using EQU, i was simply using == to check for equivilance.
Much thanks for any assistance given!
1 - Missing spaces
If %Running% EQU 0 (...
^ This space is needed
2 - In batch files lines of code are executed one after the other unless one command changes this behaviour. You can iterate with for, jump with goto, call subroutines with call, leave the batch, the subroutine or the console with exit, ... but a label will not break the execution. After your if %Running% EQU 1 ... there isn't anything that prevent execution to continue into the code following code it none of the if tests find a coincidence. So, if the set /p does not retrieve 0 or 1 the code after :ProgramNotRunning will be always executed.
3 - Missing/empty file. If IsRunning.txt can not be found or it is empty (or at least the first line is empty) or if it does contain an unexpected value, the if lines will fail. The code executed is
file missing : if EQU 0 (
line/file empty : if EQU 0 (
bad data : if this is a test EQU 0 (
All this cases will cause the line to be considered an error and the execution will be canceled.
#echo off
setlocal enableextensions disabledelayedexpansion
rem Retrieve running state
set "Running="
if exist "IsRunning.txt" (
set /p "Running=" < "IsRunning.txt"
)
IF "%Running%" EQU "0" goto ProgramNotRunning
IF "%Running%" EQU "1" goto ProgramRunning
rem As there is no valid data, assume the program is not running
:ProgramNotRunning
echo program starting
>"IsRunning.txt" (echo 1)
goto :eof
:ProgramRunning
echo program already running
goto :eof
Why >"IsRunning.txt" (echo 1)? Just to be sure there are no aditional spaces after the 1 that will be included in the output (as happens with your code), retrieved when the line is readed from the file and causing the if to fail
if "1 " EQU "1" ( ... This will be evaluated to false
And this still leaves cases where the data retrieved can make the code fail. For a 0/1 test, it is easier to not read the file, just test for presence of the file. If the file exist, the program is running, else it is not running.

Resources