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
Related
#Echo OFF
SET "Caminho=SomePath"
SET /A "UsoMaximo=95"
SET /A "Intervalo=3"
:LOOP
cls
For /F %%P in ('wmic cpu get loadpercentage ^| FINDSTR "[0-9]"') do (
IF %%P GTR %UsoMaximo% (
start %Caminho%
)
)
Ping -n %Intervalo% Localhost >NUL
GOTO :LOOP
I made this code based (almost cloned) on the code in this question: Batch file to restart a specific service based on the CPU of a process.
Basically, it will open a file located in "Caminho" when the CPU usage is higher than 95%.
The problem is i don't want it to open when the CPU usage is higher than 95%, i want it to open when the CPU usage is LOWER than 95%.
How can i do this? What i need to change?
Change GTR to LSS.
IF %%P GTR %UsoMaximo% (
From if /?:
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
NOT Specifies that Windows should carry out
the command only if the condition is false.
ERRORLEVEL number Specifies a true condition if the last program run
returned an exit code equal to or greater than the number
specified.
string1==string2 Specifies a true condition if the specified text strings
match.
EXIST filename Specifies a true condition if the specified filename
exists.
command Specifies the command to carry out if the condition is
met. Command can be followed by ELSE command which
will execute the command after the ELSE keyword if the
specified condition is FALSE
The ELSE clause must occur on the same line as the command after the IF. For
example:
IF EXIST filename. (
del filename.
) ELSE (
echo filename. missing.
)
The following would NOT work because the del command needs to be terminated
by a newline:
IF EXIST filename. del filename. ELSE echo filename. missing
Nor would the following work, since the ELSE command must be on the same line
as the end of the IF command:
IF EXIST filename. del filename.
ELSE echo filename. missing
The following would work if you want it all on one line:
IF EXIST filename. (del filename.) ELSE echo filename. missing
If Command Extensions are enabled IF changes as follows:
IF [/I] string1 compare-op string2 command
IF CMDEXTVERSION number command
IF DEFINED variable command
where compare-op may be one of:
EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal
and the /I switch, if specified, says to do case insensitive string
compares. The /I switch can also be used on the string1==string2 form
of IF. These comparisons are generic, in that if both string1 and
string2 are both comprised of all numeric digits, then the strings are
converted to numbers and a numeric comparison is performed.
The CMDEXTVERSION conditional works just like ERRORLEVEL, except it is
comparing against an internal version number associated with the Command
Extensions. The first version is 1. It will be incremented by one when
significant enhancements are added to the Command Extensions.
CMDEXTVERSION conditional is never true when Command Extensions are
disabled.
The DEFINED conditional works just like EXIST except it takes an
environment variable name and returns true if the environment variable
is defined.
%ERRORLEVEL% will expand into a string representation of
the current value of ERRORLEVEL, provided that there is not already
an environment variable with the name ERRORLEVEL, in which case you
will get its value instead. After running a program, the following
illustrates ERRORLEVEL use:
goto answer%ERRORLEVEL%
:answer0
echo Program had return code 0
:answer1
echo Program had return code 1
You can also use numerical comparisons above:
IF %ERRORLEVEL% LEQ 1 goto okay
%CMDCMDLINE% will expand into the original command line passed to
CMD.EXE prior to any processing by CMD.EXE, provided that there is not
already an environment variable with the name CMDCMDLINE, in which case
you will get its value instead.
%CMDEXTVERSION% will expand into a string representation of the
current value of CMDEXTVERSION, provided that there is not already
an environment variable with the name CMDEXTVERSION, in which case you
will get its value instead.
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.
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.
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.
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.