Batch file compare returning 0 when files are different
-
27-05-2021 - |
Question
I use a scheduling system on a Windows 2003 server that requires batch files to run different jobs. I have one job that checks if a file exists, compares that the file is not empty, then does something based on the results. Each time I run this, the error level returned is 0, but the files are different. I'm expecting to see a 1 returned.
I've verified the location of the files, and one file has content and the other is empty. I've setup prompts, and they they all say %ERRORLEVEL% is 0. I even moved the files to be in the same directory at the batch job, but they still show 0.
The code:
echo %ERRORLEVEL%
IF EXIST data.DON (
echo before %ERRORLEVEL%
FC data.DON ZERO.SEQ
echo after %ERRORLEVEL%
IF %ERRORLEVEL% EQU 1 GOTO :PROCESS
)
The output:
16:37:08.12 Thu 03/29/2012
>IF EXIST data.DON (
echo before 0
FC data.DON ZERO.SEQ
echo after 0
IF 0 EQU 1 GOTO :PROCESS
)
before 0
Comparing files data.DON and ZERO.SEQ
***** data.DON
Name|Date|Location
***** ZERO.SEQ
*****
after 0
I have this exact code in other jobs on the same server pointing at different data files, and it works. Any ideas of what I can try?
Solution
If you replace the value of any %variable% inside parentheses, that value is the same the variable had before enter the parentheses:
set var=Old value
( set var=New value & echo %var% )
Previous code always show: Old value
To solve this problem you must use Delayed Expansion, that is, enclose the variable in exclamation marks instead percents and add a SETLOCAL
command at beginning:
setlocal EnableDelayedExpansion
set var=Old value
( set var=New value & echo !var! )
All previous description also apply to errorlevel variable, so replace all %errorlevel%
by !errorlevel!
in your code and insert the previous SETLOCAL ...
.
OTHER TIPS
The correct way to check errorlevel
is like this:
IF EXIST data.DON (
FC data.DON ZERO.SEQ
IF ERRORLEVEL 1 GOTO :PROCESS
)