This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
62} How can I compare within a script if two files are identical?
@echo off & setlocal enableextensions
set file1_=c:\_d\test\My test file.txt
set file2_=c:\_d\test\My test file2.txt
if not exist "%file1_%" (
echo File "%file1_%" not found
goto :EOF)
if not exist "%file2_%" (
echo File "%file2_%" not found
goto :EOF)
::
fc /b "%file1_%" "%file2_%">nul
echo %file1_%
echo %file2_%
if %errorlevel% EQU 0 (
echo The files agree
) else (
echo The files differ)
endlocal & goto :EOF
One could also write
@echo off & setlocal enableextensions
set file1_=c:\_d\test\My test file.txt
set file2_=c:\_d\test\My test file2.txt
echo %file1_%
echo %file2_%
fc /b "%file1_%" "%file2_%">nul
&&echo Agree
||echo Differ
endlocal & goto :EOF
The output could be e.g.
C:\_D\TEST>cmdfaq
c:\_d\test\My test file.txt
c:\_d\test\My test file2.txt
Differ
Run the command following && only if the command preceding the symbol is successful.
Run the command following || only if the command preceding || fails.
If you have a DIFF.EXE UNIX port that returns an errorlevel, then you
could replace
fc /b "%file1_%" "%file2_%">nul
with
diff "%file1_%" "%file2_%">nul
However, if you have an OS version where FC (or DIFF) does not return
an errorlevel then you have to utilize FIND (or FINDSTR) in conjunction
with FC to get the errorlevel.
@echo off & setlocal enableextensions
:
fc /b "%file1_%" "%file2_%"|find "FC: no differences encountered">nul
:
endlocal & goto :EOF
Also see
Item #7.