嵌套循环错误批处理脚本处理 [英] Nested loop error handling in batch script

查看:290
本文介绍了嵌套循环错误批处理脚本处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了嵌套循环文件比较批处理脚本。

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 )))

逻辑来执行的是:
一个。如果1和2和3和4是不同的 - 回波1

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

乙。如果1和2是不同的,但不是3和4 - 回波2

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

而如果没有差异,即如果条件不进入这个code是工作的罚款。如果我尝试回声2做要求,实际上显示的回波1.不知道如何纠正这一点。

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.

推荐答案

当行的解析器prepares行或块(括号线),所有的变量读取被替换变量中的值<强>在开始执行code,所以你的%ERRORLEVEL%检查的第一个内部如果将使用当所有的块被解析的是使用相同的ERRORLEVEL值。

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.

您可以用延迟扩展( SETLOCAL enabledelayedexpansion ),并取代在需要的地方,从%VAR%!无功!,指示该读操作必须被延迟,直到命令的执行解析器。

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.

或者,你可以改变的方式来检查错误级别值,从如果%ERRORLEVEL%EQU ... 如果错误级别ñ如果错误级别值等于或高于指定的 N 值时,这将是真实的。

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
    )
)

这篇关于嵌套循环错误批处理脚本处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆