Correct Testing Precedence of Batch File ERRORLEVELs

This article was previously published under Q39585
This article has been archived. It is offered "as is" and will no longer be updated.
SUMMARY
When you use multiple IF ERRORLEVEL statements in batch files, the order inwhich the ERRORLEVELs are tested numerically is important. The correctorder is descending (highest to lowest). This ordering is from the wayERRORLEVELs are tested. The IF condition is set to TRUE when the ERRORLEVELis equal to, or greater than, the ERRORLEVEL number.
MORE INFORMATION
The following batch file fragment demonstrates this INCORRECT behavior:
   rem (execute a program which returns an errorlevel of 0 or 1)   if errorlevel 0 goto ZERO   if errorlevel 1 goto ONE   goto END   :ZERO     echo a Zero was returned!     goto END   :ONE     echo a One was returned!   :END				
The above example always branches to the "ZERO" label, regardless ofsuccess or failure. This example would work correctly if the ERRORLEVELtesting was made in descending order.

The CORRECT way to write such a batch file is as follows:
   rem (execute a program which returns an errorlevel of 0 or 1)   if errorlevel 1 goto ONE   if errorlevel 0 goto ZERO   goto END   :ZERO     echo a Zero was returned!     goto END   :ONE     echo a One was returned!   :END				
6.22 2.x 3.x 4.00 4.01 5.00 5.00a 6.00 6.20 \* yeswin4
Properties

Article ID: 39585 - Last Review: 12/04/2015 09:03:13 - Revision: 2.0

Microsoft MS-DOS 2.11 Standard Edition, Microsoft MS-DOS 3.1, Microsoft MS-DOS 3.2 Standard Edition, Microsoft MS-DOS 3.21 Standard Edition, Microsoft MS-DOS 3.3 Standard Edition, Microsoft MS-DOS 3.3a, Microsoft MS-DOS 4.0 Standard Edition, Microsoft MS-DOS 4.01 Standard Edition, Microsoft MS-DOS 5.0 Standard Edition, Microsoft MS-DOS 5.0a, Microsoft MS-DOS 6.0 Standard Edition, Microsoft MS-DOS 6.2 Standard Edition, Microsoft MS-DOS 6.21 Standard Edition, Microsoft MS-DOS 6.22 Standard Edition

  • kbnosurvey kbarchive KB39585
Feedback