0

I have written a nested loop for file compare in batch script.

fc 1.txt 2.txt | findstr "no diff" 

IF %ERRORLEVEL% EQU 1 (

fc 3.txt 4.txt | findstr "no diff"

IF %ERRORLEVEL% EQU 1 (
echo 1
goto exit
) ELSE ( 
echo 2
goto exit )))

Logic to execute is: a. If 1&2 and 3&4 are different - echo 1

b. If 1&2 are different but not 3&4 - echo 2

While this code is working fine if there are no differences ie doesn't enter "if" condition. If I try to do requirement for echo 2, it is actually showing echo 1. Not sure how to correct this.

2 Answers 2

1

When the parser prepares the lines or blocks of lines (lines in parenthesis), all the variable reads are replaced with the value in the variable before starting to execute the code, so your %errorlevel% check inside the first if will use the same errorlevel value that was used when all the block was parsed.

You can solve it using delayed expansion (setlocal enabledelayedexpansion) and replacing where needed the read operation in the variable from %var% into !var!, indicating to the parser that the read operation must be delayed until the execution of the command.

Or you can change the way to check for the errorlevel value, from if %errorlevel% equ ... into if errorlevel n that will be true if the errorlevel value is equal or greater than the indicated n value.

In this case it is using a language construct that does not involve variable read operations and is not affected by value replacements at parse time

fc 1.txt 2.txt >nul
if errorlevel 1 (
    fc 3.txt 4.txt >nul
    if errorlevel 1 (
        echo 1
    ) else (
        echo 2
    )
)
Sign up to request clarification or add additional context in comments.

Comments

1

Here's another way to do it.

fc 1.txt 2.txt | findstr "no diff" && goto :done
fc 3.txt 4.txt | findstr "no diff" && (echo 2 & goto :done)
echo 1
:done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.